diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/colorlog-6.10.1.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/colorlog-6.10.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ef3747bad8bc502664a46c8971e1ac6962ac60a8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/colorlog-6.10.1.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2012-2021 Sam Clements + +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/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataproperty-1.1.1.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataproperty-1.1.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..81ab44fad68d40ddcb3f1a7ba147308be965dbad --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/dataproperty-1.1.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016-2026 Tsuyoshi Hombashi + +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/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05eb917be3786e05cbdf9e3781749e7a896fae60 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/codec.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/codec.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d0cef933366b10c6b28a7ae1b5767e3e83c8865 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/codec.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/compat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9025731228e1edadf17b34022c0161c340042c90 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/compat.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/core.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1990b01796ca6f51883014c4b77297ff7c0ac39f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/core.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/intranges.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/intranges.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74a28be3306f6ee1c3166a23350cad230ea1fb25 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/intranges.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/package_data.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/package_data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2c1524cf9fc0305055b6d5dc4b546dfc1b96256 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/idna/__pycache__/package_data.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/jsonschema_specifications-2025.9.1.dist-info/licenses/COPYING b/data/conda_envs/evalclaw/lib/python3.11/site-packages/jsonschema_specifications-2025.9.1.dist-info/licenses/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..a9f853e43069b8e3f8a156a4af2b1198a004230d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/jsonschema_specifications-2025.9.1.dist-info/licenses/COPYING @@ -0,0 +1,19 @@ +Copyright (c) 2022 Julian Berman + +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/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc7c660c95f84d85242aa72c127057bd7adc4f71 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5a5bfd44580fb590e4923b4f2258d6ce4b6a3a4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/_version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f059cb899f7d132676ecc55f12c7527569aeb2da Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/__pycache__/utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..824c203987eb71f00b69267422719638377b6e07 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__init__.py @@ -0,0 +1,18 @@ +""" +Things that rely on the LLVM library +""" +from .dylib import * +from .executionengine import * +from .initfini import * +from .linker import * +from .module import * +from .options import * +from .newpassmanagers import * +from .targets import * +from .value import * +from .typeref import * +from .analysis import * +from .object_file import * +from .context import * +from .orcjit import * +from .config import * diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21bfcdc7162d4ddc2b7f6844af142a116fcf74ea Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/analysis.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/analysis.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2661764c2f39f6202c4f40f7d4432f89dbe2de38 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/analysis.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/common.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13478b62ef9dec7f3c543531773c9279ba2973b1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/common.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bf5253d9a9c19eef7e55262c2aafede871f280a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/config.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/context.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/context.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2ae326399e93f18eb858fabd66494d5d4972cf9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/context.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/dylib.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/dylib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d277f92ac21660b78e2a9c1ad8dac95d5c545548 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/dylib.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99dab651e483f89f07d5c807b8f97a2b5d5dafc2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/ffi.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/ffi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5bb9ccd1e0d148e6c5a561cef5267a9db7aab39 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/ffi.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/initfini.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/initfini.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ed0f0159dddc8ee9898e7b69d95ffe16d383b25 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/initfini.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/linker.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/linker.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd9e209f6c32844abad07c95ee7f1bebeca81d51 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/linker.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/module.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/module.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df975c55d5f55bc00598cc1613ddef31e209cdea Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/module.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/newpassmanagers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/newpassmanagers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41531310895bb83e6860f86755f646d396d4638d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/newpassmanagers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/object_file.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/object_file.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a5e8ed94f6f86c17c0df5207891546a52e96231 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/object_file.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/options.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/options.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33450c5677479bfea5269ebf099219fe5dfe0f45 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/options.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d21ee1c7c08586dc36049f27df98357ea92004a7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/targets.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/targets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c53554b2c7bc1515d4ef15142ee7b113294b9089 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/targets.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/typeref.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/typeref.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2558d76ea7cd1b6ec81b4a93a9d1de655f663dd5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/typeref.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/value.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/value.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e602fa33fbb68050bd264c9300da23a91a7c151c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/__pycache__/value.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/analysis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2692bf9c58478972ba4d2ce7f4a9c55bc0a068 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/analysis.py @@ -0,0 +1,69 @@ +""" +A collection of analysis utilities +""" + +from ctypes import POINTER, c_char_p, c_int + +from llvmlite.binding import ffi +from llvmlite.binding.module import parse_assembly + + +def get_function_cfg(func, show_inst=True): + """Return a string of the control-flow graph of the function in DOT + format. If the input `func` is not a materialized function, the module + containing the function is parsed to create an actual LLVM module. + The `show_inst` flag controls whether the instructions of each block + are printed. + """ + assert func is not None + from llvmlite import ir + if isinstance(func, ir.Function): + mod = parse_assembly(str(func.module)) + func = mod.get_function(func.name) + + # Assume func is a materialized function + with ffi.OutputString() as dotstr: + ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst) + return str(dotstr) + + +def view_dot_graph(graph, filename=None, view=False): + """ + View the given DOT source. If view is True, the image is rendered + and viewed by the default application in the system. The file path of + the output is returned. If view is False, a graphviz.Source object is + returned. If view is False and the environment is in a IPython session, + an IPython image object is returned and can be displayed inline in the + notebook. + + This function requires the graphviz package. + + Args + ---- + - graph [str]: a DOT source code + - filename [str]: optional. if given and view is True, this specifies + the file path for the rendered output to write to. + - view [bool]: if True, opens the rendered output file. + + """ + # Optionally depends on graphviz package + import graphviz as gv + + src = gv.Source(graph) + if view: + # Returns the output file path + return src.render(filename, view=view) + else: + # Attempts to show the graph in IPython notebook + try: + __IPYTHON__ + except NameError: + return src + else: + import IPython.display as display + format = 'svg' + return display.SVG(data=src.pipe(format)) + + +# Ctypes binding +ffi.lib.LLVMPY_WriteCFG.argtypes = [ffi.LLVMValueRef, POINTER(c_char_p), c_int] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/common.py new file mode 100644 index 0000000000000000000000000000000000000000..3f5746a5b057e76b1bf7b33c2892de1640919519 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/common.py @@ -0,0 +1,34 @@ +import atexit + + +def _encode_string(s): + encoded = s.encode('utf-8') + return encoded + + +def _decode_string(b): + return b.decode('utf-8') + + +_encode_string.__doc__ = """Encode a string for use by LLVM.""" +_decode_string.__doc__ = """Decode a LLVM character (byte)string.""" + + +_shutting_down = [False] + + +def _at_shutdown(): + _shutting_down[0] = True + + +atexit.register(_at_shutdown) + + +def _is_shutting_down(_shutting_down=_shutting_down): + """ + Whether the interpreter is currently shutting down. + For use in finalizers, __del__ methods, and similar; it is advised + to early bind this function rather than look it up when calling it, + since at shutdown module globals may be cleared. + """ + return _shutting_down[0] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/config.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/config.py new file mode 100644 index 0000000000000000000000000000000000000000..3931fe39eb7ef0e0148447e482cba7f387b686aa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/config.py @@ -0,0 +1,143 @@ +import os +import warnings +from functools import cache +from ctypes import c_int, c_char_p +from llvmlite.binding import ffi + +# these are here as they cannot be lazy bound as the module globals make calls +# to the LLVMPY API functions +ffi.lib.LLVMPY_HasSVMLSupport.argtypes = () +ffi.lib.LLVMPY_HasSVMLSupport.restype = c_int + +ffi.lib.LLVMPY_IsStaticLibstdcxxLinkageBuild.argtypes = () +ffi.lib.LLVMPY_IsStaticLibstdcxxLinkageBuild.restype = c_int + +ffi.lib.LLVMPY_IsDynamicLLVMLinkageBuild.argtypes = () +ffi.lib.LLVMPY_IsDynamicLLVMLinkageBuild.restype = c_int + +ffi.lib.LLVMPY_PackageFormat.argtypes = () +ffi.lib.LLVMPY_PackageFormat.restype = c_char_p + +ffi.lib.LLVMPY_LlvmAssertionsState.argtypes = () +ffi.lib.LLVMPY_LlvmAssertionsState.restype = c_char_p + + +def _has_svml(): + """ + Returns True if SVML was enabled at FFI support compile time. + """ + if ffi.lib.LLVMPY_HasSVMLSupport() == 0: + return False + else: + return True + + +has_svml = _has_svml() + + +def _build_llvm_linkage_type(): + """ + Returns "static" if the FFI support is statically linked against LLVM, + returns "dynamic" otherwise. + """ + if ffi.lib.LLVMPY_IsDynamicLLVMLinkageBuild() == 0: + return "static" + else: + return "dynamic" + + +build_llvm_linkage_type = _build_llvm_linkage_type() + + +def _build_libstdcxx_linkage_type(): + """ + Returns "static" if the FFI support is statically linked against libstdc++, + returns "dynamic" otherwise. + """ + if ffi.lib.LLVMPY_IsStaticLibstdcxxLinkageBuild() == 1: + return "static" + else: + return "dynamic" + + +build_libstdcxx_linkage_type = _build_libstdcxx_linkage_type() + + +def _package_format(): + """ + Returns "wheel", "conda" or "unspecified" + """ + return ffi.lib.LLVMPY_PackageFormat().decode() + + +package_format = _package_format() + + +def _llvm_assertions_state(): + """ + Returns one of "on", "off" or "unknown". Depending on whether it is + determined that LLVM was build with assertions on, off, or is not known. + "Is not known" is typically from a dynamic linkage against LLVM in which + case it's not easily identified whether LLVM was built with assertions. + """ + return ffi.lib.LLVMPY_LlvmAssertionsState().decode() + + +llvm_assertions_state = _llvm_assertions_state() + + +@cache +def get_sysinfo(): + d = dict() + d["ffi_lib_location"] = ffi.lib._name + d["package_format"] = package_format + d["llvm_linkage_type"] = build_llvm_linkage_type + d["libstdcxx_linkage_type"] = build_libstdcxx_linkage_type + d["llvm_assertions_state"] = llvm_assertions_state + + # import lief + HAVE_LIEF = False + try: + import lief + HAVE_LIEF = True + except ImportError: + msg = "py-lief package not found, sysinfo is limited as a result" + warnings.warn(msg) + + d["lief_probe_status"] = HAVE_LIEF + d["linked_libraries"] = None + d["canonicalised_linked_libraries"] = None + + def canonicalise_library_type(dso): + """Canonicalises the representation of the binary::libraries as a + sequence of strings""" + # Note lief v16: + # Mach-O .libraries are DylibCommand instances. + # Windows PE and Linux ELF .libraries are strings. + return [getattr(x, "name", x) for x in dso.libraries] + + def canonicalise_library_spelling(libs): + # This adjusts the library "spelling" so that it just contains the + # name given to the linker. e.g. `@rpath/somewhere/libfoo.so.1.3` + # would be canonicalised to "foo". + fixes = [] + for lib in libs: + # some libraries, e.g. Mach-O have an @rpath or system path + # prefix in their name, remove it. + path_stripped = os.path.split(lib)[-1] + # Assume all library names contain at least one dot, even if they + # don't it's fine, the first part is the piece of interest. + prefix_libname = path_stripped.split(".")[0] + linker_name = prefix_libname.replace("lib", "").replace("LIB", "") + # further canonicalize by referring to all libraries in lower case. + fixes.append(linker_name.lower()) + return fixes + + if HAVE_LIEF: + dso = lief.parse(d["ffi_lib_location"]) + link_libs = tuple(canonicalise_library_type(dso)) + d["linked_libraries"] = link_libs + canonicalised_libs = canonicalise_library_spelling(link_libs) + d["canonicalised_linked_libraries"] = canonicalised_libs + + return d diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/context.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/context.py new file mode 100644 index 0000000000000000000000000000000000000000..85a256dd153a7e51446b5933a94381f97fee58ee --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/context.py @@ -0,0 +1,31 @@ +from llvmlite.binding import ffi + + +def create_context(): + return ContextRef( + ffi.lib.LLVMPY_ContextCreate()) + + +def get_global_context(): + return GlobalContextRef( + ffi.lib.LLVMPY_GetGlobalContext()) + + +class ContextRef(ffi.ObjectRef): + def __init__(self, context_ptr): + super(ContextRef, self).__init__(context_ptr) + + def _dispose(self): + ffi.lib.LLVMPY_ContextDispose(self) + + +class GlobalContextRef(ContextRef): + def _dispose(self): + pass + + +ffi.lib.LLVMPY_GetGlobalContext.restype = ffi.LLVMContextRef + +ffi.lib.LLVMPY_ContextCreate.restype = ffi.LLVMContextRef + +ffi.lib.LLVMPY_ContextDispose.argtypes = [ffi.LLVMContextRef] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/dylib.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/dylib.py new file mode 100644 index 0000000000000000000000000000000000000000..e22542c496b7baadc002333f28e14a91e63a359a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/dylib.py @@ -0,0 +1,45 @@ +from ctypes import c_void_p, c_char_p, c_bool, POINTER + +from llvmlite.binding import ffi +from llvmlite.binding.common import _encode_string + + +def address_of_symbol(name): + """ + Get the in-process address of symbol named *name*. + An integer is returned, or None if the symbol isn't found. + """ + return ffi.lib.LLVMPY_SearchAddressOfSymbol(_encode_string(name)) + + +def add_symbol(name, address): + """ + Register the *address* of global symbol *name*. This will make + it usable (e.g. callable) from LLVM-compiled functions. + """ + ffi.lib.LLVMPY_AddSymbol(_encode_string(name), c_void_p(address)) + + +def load_library_permanently(filename): + """ + Load an external library + """ + with ffi.OutputString() as outerr: + if ffi.lib.LLVMPY_LoadLibraryPermanently( + _encode_string(filename), outerr): + raise RuntimeError(str(outerr)) + +# ============================================================================ +# FFI + + +ffi.lib.LLVMPY_AddSymbol.argtypes = [ + c_char_p, + c_void_p, +] + +ffi.lib.LLVMPY_SearchAddressOfSymbol.argtypes = [c_char_p] +ffi.lib.LLVMPY_SearchAddressOfSymbol.restype = c_void_p + +ffi.lib.LLVMPY_LoadLibraryPermanently.argtypes = [c_char_p, POINTER(c_char_p)] +ffi.lib.LLVMPY_LoadLibraryPermanently.restype = c_bool diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/executionengine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/executionengine.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba0985ef618ba3d497da8fbf2ee24c7f291c2ec --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/executionengine.py @@ -0,0 +1,330 @@ +import platform +from ctypes import (POINTER, c_char_p, c_bool, c_void_p, + c_int, c_uint64, c_size_t, CFUNCTYPE, string_at, cast, + py_object, Structure) + +from llvmlite.binding import ffi, targets, object_file + + +# Just check these weren't optimized out of the DLL. +ffi.lib.LLVMPY_LinkInMCJIT + + +def create_mcjit_compiler(module, target_machine, use_lmm=None): + """ + Create a MCJIT ExecutionEngine from the given *module* and + *target_machine*. + + *lmm* controls whether the llvmlite memory manager is used. If not supplied, + the default choice for the platform will be used (``True`` on 64-bit ARM + systems, ``False`` otherwise). + """ + if use_lmm is None: + use_lmm = platform.machine() in ('arm64', 'aarch64') + + with ffi.OutputString() as outerr: + engine = ffi.lib.LLVMPY_CreateMCJITCompiler( + module, target_machine, use_lmm, outerr) + if not engine: + raise RuntimeError(str(outerr)) + + target_machine._owned = True + return ExecutionEngine(engine, module=module) + + +def check_jit_execution(): + """ + Check the system allows execution of in-memory JITted functions. + An exception is raised otherwise. + """ + errno = ffi.lib.LLVMPY_TryAllocateExecutableMemory() + if errno != 0: + raise OSError(errno, + "cannot allocate executable memory. " + "This may be due to security restrictions on your " + "system, such as SELinux or similar mechanisms." + ) + + +class ExecutionEngine(ffi.ObjectRef): + """An ExecutionEngine owns all Modules associated with it. + Deleting the engine will remove all associated modules. + It is an error to delete the associated modules. + """ + _object_cache = None + + def __init__(self, ptr, module): + """ + Module ownership is transferred to the EE + """ + self._modules = set([module]) + self._td = None + module._owned = True + ffi.ObjectRef.__init__(self, ptr) + + def get_function_address(self, name): + """ + Return the address of the function named *name* as an integer. + + It's a fatal error in LLVM if the symbol of *name* doesn't exist. + """ + return ffi.lib.LLVMPY_GetFunctionAddress(self, name.encode("ascii")) + + def get_global_value_address(self, name): + """ + Return the address of the global value named *name* as an integer. + + It's a fatal error in LLVM if the symbol of *name* doesn't exist. + """ + return ffi.lib.LLVMPY_GetGlobalValueAddress(self, name.encode("ascii")) + + def add_global_mapping(self, gv, addr): + ffi.lib.LLVMPY_AddGlobalMapping(self, gv, addr) + + def add_module(self, module): + """ + Ownership of module is transferred to the execution engine + """ + if module in self._modules: + raise KeyError("module already added to this engine") + ffi.lib.LLVMPY_AddModule(self, module) + module._owned = True + self._modules.add(module) + + def finalize_object(self): + """ + Make sure all modules owned by the execution engine are fully processed + and "usable" for execution. + """ + ffi.lib.LLVMPY_FinalizeObject(self) + + def run_static_constructors(self): + """ + Run static constructors which initialize module-level static objects. + """ + ffi.lib.LLVMPY_RunStaticConstructors(self) + + def run_static_destructors(self): + """ + Run static destructors which perform module-level cleanup of static + resources. + """ + ffi.lib.LLVMPY_RunStaticDestructors(self) + + def remove_module(self, module): + """ + Ownership of module is returned + """ + with ffi.OutputString() as outerr: + if ffi.lib.LLVMPY_RemoveModule(self, module, outerr): + raise RuntimeError(str(outerr)) + self._modules.remove(module) + module._owned = False + + @property + def target_data(self): + """ + The TargetData for this execution engine. + """ + if self._td is not None: + return self._td + ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self) + self._td = targets.TargetData(ptr) + self._td._owned = True + return self._td + + def enable_jit_events(self): + """ + Enable JIT events for profiling of generated code. + Return value indicates whether connection to profiling tool + was successful. + """ + ret = ffi.lib.LLVMPY_EnableJITEvents(self) + return ret + + def _find_module_ptr(self, module_ptr): + """ + Find the ModuleRef corresponding to the given pointer. + """ + ptr = cast(module_ptr, c_void_p).value + for module in self._modules: + if cast(module._ptr, c_void_p).value == ptr: + return module + return None + + def add_object_file(self, obj_file): + """ + Add object file to the jit. object_file can be instance of + :class:ObjectFile or a string representing file system path + """ + if isinstance(obj_file, str): + obj_file = object_file.ObjectFileRef.from_path(obj_file) + + ffi.lib.LLVMPY_MCJITAddObjectFile(self, obj_file) + + def set_object_cache(self, notify_func=None, getbuffer_func=None): + """ + Set the object cache "notifyObjectCompiled" and "getBuffer" + callbacks to the given Python functions. + """ + self._object_cache_notify = notify_func + self._object_cache_getbuffer = getbuffer_func + # Lifetime of the object cache is managed by us. + self._object_cache = _ObjectCacheRef(self) + # Note this doesn't keep a reference to self, to avoid reference + # cycles. + ffi.lib.LLVMPY_SetObjectCache(self, self._object_cache) + + def _raw_object_cache_notify(self, data): + """ + Low-level notify hook. + """ + if self._object_cache_notify is None: + return + module_ptr = data.contents.module_ptr + buf_ptr = data.contents.buf_ptr + buf_len = data.contents.buf_len + buf = string_at(buf_ptr, buf_len) + module = self._find_module_ptr(module_ptr) + if module is None: + # The LLVM EE should only give notifications for modules + # known by us. + raise RuntimeError("object compilation notification " + "for unknown module %s" % (module_ptr,)) + self._object_cache_notify(module, buf) + + def _raw_object_cache_getbuffer(self, data): + """ + Low-level getbuffer hook. + """ + if self._object_cache_getbuffer is None: + return + module_ptr = data.contents.module_ptr + module = self._find_module_ptr(module_ptr) + if module is None: + # The LLVM EE should only give notifications for modules + # known by us. + raise RuntimeError("object compilation notification " + "for unknown module %s" % (module_ptr,)) + + buf = self._object_cache_getbuffer(module) + if buf is not None: + # Create a copy, which will be freed by the caller + data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf)) + data[0].buf_len = len(buf) + + def _dispose(self): + # The modules will be cleaned up by the EE + for mod in self._modules: + mod.detach() + if self._td is not None: + self._td.detach() + self._modules.clear() + self._object_cache = None + self._capi.LLVMPY_DisposeExecutionEngine(self) + + +class _ObjectCacheRef(ffi.ObjectRef): + """ + Internal: an ObjectCache instance for use within an ExecutionEngine. + """ + + def __init__(self, obj): + ptr = ffi.lib.LLVMPY_CreateObjectCache(_notify_c_hook, + _getbuffer_c_hook, + obj) + ffi.ObjectRef.__init__(self, ptr) + + def _dispose(self): + self._capi.LLVMPY_DisposeObjectCache(self) + + +# ============================================================================ +# FFI + + +ffi.lib.LLVMPY_CreateMCJITCompiler.argtypes = [ + ffi.LLVMModuleRef, + ffi.LLVMTargetMachineRef, + c_bool, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_CreateMCJITCompiler.restype = ffi.LLVMExecutionEngineRef + +ffi.lib.LLVMPY_RemoveModule.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMModuleRef, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_RemoveModule.restype = c_bool + +ffi.lib.LLVMPY_AddModule.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMModuleRef +] + +ffi.lib.LLVMPY_AddGlobalMapping.argtypes = [ffi.LLVMExecutionEngineRef, + ffi.LLVMValueRef, + c_void_p] + +ffi.lib.LLVMPY_FinalizeObject.argtypes = [ffi.LLVMExecutionEngineRef] + +ffi.lib.LLVMPY_GetExecutionEngineTargetData.argtypes = [ + ffi.LLVMExecutionEngineRef +] +ffi.lib.LLVMPY_GetExecutionEngineTargetData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_TryAllocateExecutableMemory.argtypes = [] +ffi.lib.LLVMPY_TryAllocateExecutableMemory.restype = c_int + +ffi.lib.LLVMPY_GetFunctionAddress.argtypes = [ + ffi.LLVMExecutionEngineRef, + c_char_p +] +ffi.lib.LLVMPY_GetFunctionAddress.restype = c_uint64 + +ffi.lib.LLVMPY_GetGlobalValueAddress.argtypes = [ + ffi.LLVMExecutionEngineRef, + c_char_p +] +ffi.lib.LLVMPY_GetGlobalValueAddress.restype = c_uint64 + +ffi.lib.LLVMPY_MCJITAddObjectFile.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMObjectFileRef +] + + +class _ObjectCacheData(Structure): + _fields_ = [ + ('module_ptr', ffi.LLVMModuleRef), + ('buf_ptr', c_void_p), + ('buf_len', c_size_t), + ] + + +_ObjectCacheNotifyFunc = CFUNCTYPE(None, py_object, + POINTER(_ObjectCacheData)) +_ObjectCacheGetBufferFunc = CFUNCTYPE(None, py_object, + POINTER(_ObjectCacheData)) + +# XXX The ctypes function wrappers are created at the top-level, otherwise +# there are issues when creating CFUNCTYPEs in child processes on CentOS 5 +# 32 bits. +_notify_c_hook = _ObjectCacheNotifyFunc( + ExecutionEngine._raw_object_cache_notify) +_getbuffer_c_hook = _ObjectCacheGetBufferFunc( + ExecutionEngine._raw_object_cache_getbuffer) + +ffi.lib.LLVMPY_CreateObjectCache.argtypes = [_ObjectCacheNotifyFunc, + _ObjectCacheGetBufferFunc, + py_object] +ffi.lib.LLVMPY_CreateObjectCache.restype = ffi.LLVMObjectCacheRef + +ffi.lib.LLVMPY_DisposeObjectCache.argtypes = [ffi.LLVMObjectCacheRef] + +ffi.lib.LLVMPY_SetObjectCache.argtypes = [ffi.LLVMExecutionEngineRef, + ffi.LLVMObjectCacheRef] + +ffi.lib.LLVMPY_CreateByteString.restype = c_void_p +ffi.lib.LLVMPY_CreateByteString.argtypes = [c_void_p, c_size_t] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/ffi.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/ffi.py new file mode 100644 index 0000000000000000000000000000000000000000..1732af6cf276688bfed050553fbeebebb68b40c2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/ffi.py @@ -0,0 +1,410 @@ +import sys +import ctypes +import threading +import importlib.resources as _impres + +from llvmlite.binding.common import _decode_string, _is_shutting_down +from llvmlite.utils import get_library_name + + +def _make_opaque_ref(name): + newcls = type(name, (ctypes.Structure,), {}) + return ctypes.POINTER(newcls) + + +LLVMContextRef = _make_opaque_ref("LLVMContext") +LLVMModuleRef = _make_opaque_ref("LLVMModule") +LLVMValueRef = _make_opaque_ref("LLVMValue") +LLVMTypeRef = _make_opaque_ref("LLVMType") +LLVMExecutionEngineRef = _make_opaque_ref("LLVMExecutionEngine") +LLVMPassManagerBuilderRef = _make_opaque_ref("LLVMPassManagerBuilder") +LLVMPassManagerRef = _make_opaque_ref("LLVMPassManager") +LLVMTargetDataRef = _make_opaque_ref("LLVMTargetData") +LLVMTargetLibraryInfoRef = _make_opaque_ref("LLVMTargetLibraryInfo") +LLVMTargetRef = _make_opaque_ref("LLVMTarget") +LLVMTargetMachineRef = _make_opaque_ref("LLVMTargetMachine") +LLVMMemoryBufferRef = _make_opaque_ref("LLVMMemoryBuffer") +LLVMAttributeListIterator = _make_opaque_ref("LLVMAttributeListIterator") +LLVMElementIterator = _make_opaque_ref("LLVMElementIterator") +LLVMAttributeSetIterator = _make_opaque_ref("LLVMAttributeSetIterator") +LLVMGlobalsIterator = _make_opaque_ref("LLVMGlobalsIterator") +LLVMFunctionsIterator = _make_opaque_ref("LLVMFunctionsIterator") +LLVMBlocksIterator = _make_opaque_ref("LLVMBlocksIterator") +LLVMArgumentsIterator = _make_opaque_ref("LLVMArgumentsIterator") +LLVMInstructionsIterator = _make_opaque_ref("LLVMInstructionsIterator") +LLVMOperandsIterator = _make_opaque_ref("LLVMOperandsIterator") +LLVMIncomingBlocksIterator = _make_opaque_ref("LLVMIncomingBlocksIterator") +LLVMTypesIterator = _make_opaque_ref("LLVMTypesIterator") +LLVMObjectCacheRef = _make_opaque_ref("LLVMObjectCache") +LLVMObjectFileRef = _make_opaque_ref("LLVMObjectFile") +LLVMSectionIteratorRef = _make_opaque_ref("LLVMSectionIterator") +LLVMOrcLLJITRef = _make_opaque_ref("LLVMOrcLLJITRef") +LLVMOrcDylibTrackerRef = _make_opaque_ref("LLVMOrcDylibTrackerRef") +LLVMTimePassesHandlerRef = _make_opaque_ref("LLVMTimePassesHandler") +LLVMPipelineTuningOptionsRef = _make_opaque_ref("LLVMPipeLineTuningOptions") +LLVMModulePassManagerRef = _make_opaque_ref("LLVMModulePassManager") +LLVMFunctionPassManagerRef = _make_opaque_ref("LLVMFunctionPassManager") +LLVMPassBuilderRef = _make_opaque_ref("LLVMPassBuilder") + + +class _LLVMLock: + """A Lock to guarantee thread-safety for the LLVM C-API. + + This class implements __enter__ and __exit__ for acquiring and releasing + the lock as a context manager. + + Also, callbacks can be attached so that every time the lock is acquired + and released the corresponding callbacks will be invoked. + """ + def __init__(self): + # The reentrant lock is needed for callbacks that re-enter + # the Python interpreter. + self._lock = threading.RLock() + self._cblist = [] + + def register(self, acq_fn, rel_fn): + """Register callbacks that are invoked immediately after the lock is + acquired (``acq_fn()``) and immediately before the lock is released + (``rel_fn()``). + """ + self._cblist.append((acq_fn, rel_fn)) + + def unregister(self, acq_fn, rel_fn): + """Remove the registered callbacks. + """ + self._cblist.remove((acq_fn, rel_fn)) + + def __enter__(self): + self._lock.acquire() + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + acq_fn() + + def __exit__(self, *exc_details): + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + rel_fn() + self._lock.release() + + +class _suppress_cleanup_errors: + def __init__(self, context): + self._context = context + + def __enter__(self): + return self._context.__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + try: + return self._context.__exit__(exc_type, exc_value, traceback) + except PermissionError: + pass # Resource dylibs can't be deleted on Windows. + + +class _lib_wrapper(object): + """Wrap libllvmlite with a lock such that only one thread may access it at + a time. + + This class duck-types a CDLL. + """ + __slots__ = ['_lib_handle', '_fntab', '_lock'] + + def __init__(self): + self._lib_handle = None + self._fntab = {} + self._lock = _LLVMLock() + + def _load_lib(self): + test_sym = "LLVMPY_GetVersionInfo" + mod_name = __name__.rpartition(".")[0] + lib_name = get_library_name() + + with _suppress_cleanup_errors(_importlib_resources_path( + mod_name, lib_name)) as lib_path: + try: + self._lib_handle = ctypes.CDLL(str(lib_path)) + # Check that we can look up expected symbols. + getattr(self._lib_handle, test_sym)() + except OSError: + # OSError may be raised if the file cannot be opened, or is not + # a shared library. + msg = (f"Could not find/load shared object file '{lib_name}' " + f"from resource location: '{mod_name}'. This could mean " + "that the library literally cannot be found, but may " + "also mean that the permissions are incorrect or that a " + "dependency of/a symbol in the library could not be " + "resolved.") + raise OSError(msg) + except AttributeError: + # AttributeError is raised if the test_sym symbol does not + # exist. + msg = ("During testing of symbol lookup, the symbol " + f"'{test_sym}' could not be found in the library " + f"'{lib_path}'") + raise OSError(msg) + + @property + def _lib(self): + # Not threadsafe. + if not self._lib_handle: + self._load_lib() + return self._lib_handle + + def __getattr__(self, name): + try: + return self._fntab[name] + except KeyError: + pass + # Lazily wraps new functions as they are requested + cfn = getattr(self._lib, name) + wrapped = _lib_fn_wrapper(self._lock, cfn) + self._fntab[name] = wrapped + return wrapped + + @property + def _name(self): + """The name of the library passed in the CDLL constructor. + + For duck-typing a ctypes.CDLL + """ + return self._lib._name + + @property + def _handle(self): + """The system handle used to access the library. + + For duck-typing a ctypes.CDLL + """ + return self._lib._handle + + +class _lib_fn_wrapper(object): + """Wraps and duck-types a ctypes.CFUNCTYPE to provide + automatic locking when the wrapped function is called. + + TODO: we can add methods to mark the function as threadsafe + and remove the locking-step on call when marked. + """ + __slots__ = ['_lock', '_cfn'] + + def __init__(self, lock, cfn): + self._lock = lock + self._cfn = cfn + + @property + def argtypes(self): + return self._cfn.argtypes + + @argtypes.setter + def argtypes(self, argtypes): + self._cfn.argtypes = argtypes + + @property + def restype(self): + return self._cfn.restype + + @restype.setter + def restype(self, restype): + self._cfn.restype = restype + + def __call__(self, *args, **kwargs): + with self._lock: + return self._cfn(*args, **kwargs) + + +def _importlib_resources_path_repl(package, resource): + """Replacement implementation of `import.resources.path` to avoid + deprecation warning following code at importlib_resources/_legacy.py + as suggested by https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy + + Notes on differences from importlib.resources implementation: + + The `_common.normalize_path(resource)` call is skipped because it is an + internal API and it is unnecessary for the use here. What it does is + ensuring `resource` is a str and that it does not contain path separators. + """ # noqa E501 + return _impres.as_file(_impres.files(package) / resource) + + +_importlib_resources_path = (_importlib_resources_path_repl + if sys.version_info[:2] >= (3, 10) + else _impres.path) + + +lib = _lib_wrapper() + + +def register_lock_callback(acq_fn, rel_fn): + """Register callback functions for lock acquire and release. + *acq_fn* and *rel_fn* are callables that take no arguments. + """ + lib._lock.register(acq_fn, rel_fn) + + +def unregister_lock_callback(acq_fn, rel_fn): + """Remove the registered callback functions for lock acquire and release. + The arguments are the same as used in `register_lock_callback()`. + """ + lib._lock.unregister(acq_fn, rel_fn) + + +class _DeadPointer(object): + """ + Dummy class to make error messages more helpful. + """ + + +class OutputString(object): + """ + Object for managing the char* output of LLVM APIs. + """ + _as_parameter_ = _DeadPointer() + + @classmethod + def from_return(cls, ptr): + """Constructing from a pointer returned from the C-API. + The pointer must be allocated with LLVMPY_CreateString. + + Note + ---- + Because ctypes auto-converts *restype* of *c_char_p* into a python + string, we must use *c_void_p* to obtain the raw pointer. + """ + return cls(init=ctypes.cast(ptr, ctypes.c_char_p)) + + def __init__(self, owned=True, init=None): + self._ptr = init if init is not None else ctypes.c_char_p(None) + self._as_parameter_ = ctypes.byref(self._ptr) + self._owned = owned + + def close(self): + if self._ptr is not None: + if self._owned: + lib.LLVMPY_DisposeString(self._ptr) + self._ptr = None + del self._as_parameter_ + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + # Avoid errors trying to rely on globals and modules at interpreter + # shutdown. + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __str__(self): + if self._ptr is None: + return "" + s = self._ptr.value + assert s is not None + return _decode_string(s) + + def __bool__(self): + return bool(self._ptr) + + __nonzero__ = __bool__ + + @property + def bytes(self): + """Get the raw bytes of content of the char pointer. + """ + return self._ptr.value + + +def ret_string(ptr): + """To wrap string return-value from C-API. + """ + if ptr is not None: + return str(OutputString.from_return(ptr)) + + +def ret_bytes(ptr): + """To wrap bytes return-value from C-API. + """ + if ptr is not None: + return OutputString.from_return(ptr).bytes + + +class ObjectRef(object): + """ + A wrapper around a ctypes pointer to a LLVM object ("resource"). + """ + _closed = False + _as_parameter_ = _DeadPointer() + # Whether this object pointer is owned by another one. + _owned = False + + def __init__(self, ptr): + if ptr is None: + raise ValueError("NULL pointer") + self._ptr = ptr + self._as_parameter_ = ptr + self._capi = lib + + def close(self): + """ + Close this object and do any required clean-up actions. + """ + try: + if not self._closed and not self._owned: + self._dispose() + finally: + self.detach() + + def detach(self): + """ + Detach the underlying LLVM resource without disposing of it. + """ + if not self._closed: + del self._as_parameter_ + self._closed = True + self._ptr = None + + def _dispose(self): + """ + Dispose of the underlying LLVM resource. Should be overriden + by subclasses. Automatically called by close(), __del__() and + __exit__() (unless the resource has been detached). + """ + + @property + def closed(self): + """ + Whether this object has been closed. A closed object can't + be used anymore. + """ + return self._closed + + def __enter__(self): + assert hasattr(self, "close") + if self._closed: + raise RuntimeError("%s instance already closed" % (self.__class__,)) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __bool__(self): + return bool(self._ptr) + + def __eq__(self, other): + if not hasattr(other, "_ptr"): + return False + return ctypes.addressof(self._ptr[0]) == \ + ctypes.addressof(other._ptr[0]) + + __nonzero__ = __bool__ + + # XXX useful? + def __hash__(self): + return hash(ctypes.cast(self._ptr, ctypes.c_void_p).value) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/initfini.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/initfini.py new file mode 100644 index 0000000000000000000000000000000000000000..8777b4ff06446b562026d57cb3daf1c017d70299 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/initfini.py @@ -0,0 +1,85 @@ +from ctypes import c_uint + +from llvmlite.binding import ffi + + +def initialize(): + """ + Initialize the LLVM core (deprecated). + + This function is deprecated and will raise an error when called. + LLVM initialization is now handled automatically and no longer + requires explicit initialization calls. + + Raises: + RuntimeError: Always raised as this function is no longer needed. + """ + raise RuntimeError( + "llvmlite.binding.initialize() is deprecated and will be removed. " + "LLVM initialization is now handled automatically. " + "Please remove calls to this function from your code and check for " + "other behavioral changes that may have occurred due to LLVM updates." + ) + + +def initialize_all_targets(): + """ + Initialize all targets. Necessary before targets can be looked up + via the :class:`Target` class. + """ + ffi.lib.LLVMPY_InitializeAllTargetInfos() + ffi.lib.LLVMPY_InitializeAllTargets() + ffi.lib.LLVMPY_InitializeAllTargetMCs() + + +def initialize_all_asmprinters(): + """ + Initialize all code generators. Necessary before generating + any assembly or machine code via the :meth:`TargetMachine.emit_object` + and :meth:`TargetMachine.emit_assembly` methods. + """ + ffi.lib.LLVMPY_InitializeAllAsmPrinters() + + +def initialize_native_target(): + """ + Initialize the native (host) target. Necessary before doing any + code generation. + """ + ffi.lib.LLVMPY_InitializeNativeTarget() + + +def initialize_native_asmprinter(): + """ + Initialize the native ASM printer. + """ + ffi.lib.LLVMPY_InitializeNativeAsmPrinter() + + +def initialize_native_asmparser(): + """ + Initialize the native ASM parser. + """ + ffi.lib.LLVMPY_InitializeNativeAsmParser() + + +def shutdown(): + ffi.lib.LLVMPY_Shutdown() + + +# ============================================================================= +# Set function FFI + +ffi.lib.LLVMPY_GetVersionInfo.restype = c_uint + + +def _version_info(): + v = [] + x = ffi.lib.LLVMPY_GetVersionInfo() + while x: + v.append(x & 0xff) + x >>= 8 + return tuple(reversed(v)) + + +llvm_version_info = _version_info() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/linker.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/linker.py new file mode 100644 index 0000000000000000000000000000000000000000..31d1e26ffb99763af367d07c30fd77770103dc79 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/linker.py @@ -0,0 +1,20 @@ +from ctypes import c_int, c_char_p, POINTER +from llvmlite.binding import ffi + + +def link_modules(dst, src): + with ffi.OutputString() as outerr: + err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr) + # The underlying module was destroyed + src.detach() + if err: + raise RuntimeError(str(outerr)) + + +ffi.lib.LLVMPY_LinkModules.argtypes = [ + ffi.LLVMModuleRef, + ffi.LLVMModuleRef, + POINTER(c_char_p), +] + +ffi.lib.LLVMPY_LinkModules.restype = c_int diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/module.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/module.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbb1faa6545718f9226133ccef42b03a098fd37 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/module.py @@ -0,0 +1,349 @@ +from ctypes import (c_char_p, byref, POINTER, c_bool, create_string_buffer, + c_size_t, string_at) + +from llvmlite.binding import ffi +from llvmlite.binding.linker import link_modules +from llvmlite.binding.common import _decode_string, _encode_string +from llvmlite.binding.value import ValueRef, TypeRef +from llvmlite.binding.context import get_global_context + + +def parse_assembly(llvmir, context=None): + """ + Create Module from a LLVM IR string + """ + if context is None: + context = get_global_context() + llvmir = _encode_string(llvmir) + strbuf = c_char_p(llvmir) + with ffi.OutputString() as errmsg: + mod = ModuleRef( + ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg), + context) + if errmsg: + mod.close() + raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg)) + return mod + + +def parse_bitcode(bitcode, context=None): + """ + Create Module from a LLVM *bitcode* (a bytes object). + """ + if context is None: + context = get_global_context() + buf = c_char_p(bitcode) + bufsize = len(bitcode) + with ffi.OutputString() as errmsg: + mod = ModuleRef(ffi.lib.LLVMPY_ParseBitcode( + context, buf, bufsize, errmsg), context) + if errmsg: + mod.close() + raise RuntimeError( + "LLVM bitcode parsing error\n{0}".format(errmsg)) + return mod + + +class ModuleRef(ffi.ObjectRef): + """ + A reference to a LLVM module. + """ + + def __init__(self, module_ptr, context): + super(ModuleRef, self).__init__(module_ptr) + self._context = context + + def __str__(self): + with ffi.OutputString() as outstr: + ffi.lib.LLVMPY_PrintModuleToString(self, outstr) + return str(outstr) + + def as_bitcode(self): + """ + Return the module's LLVM bitcode, as a bytes object. + """ + ptr = c_char_p(None) + size = c_size_t(-1) + ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size)) + if not ptr: + raise MemoryError + try: + assert size.value >= 0 + return string_at(ptr, size.value) + finally: + ffi.lib.LLVMPY_DisposeString(ptr) + + def _dispose(self): + self._capi.LLVMPY_DisposeModule(self) + + def get_function(self, name): + """ + Get a ValueRef pointing to the function named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'function', dict(module=self)) + + def get_global_variable(self, name): + """ + Get a ValueRef pointing to the global variable named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedGlobalVariable(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'global', dict(module=self)) + + def get_struct_type(self, name): + """ + Get a TypeRef pointing to a structure type named *name*. + NameError is raised if the struct type isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedStructType(self, _encode_string(name)) + if not p: + raise NameError(name) + return TypeRef(p) + + def verify(self): + """ + Verify the module IR's correctness. RuntimeError is raised on error. + """ + with ffi.OutputString() as outmsg: + if ffi.lib.LLVMPY_VerifyModule(self, outmsg): + raise RuntimeError(str(outmsg)) + + @property + def name(self): + """ + The module's identifier. + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleName(self)) + + @name.setter + def name(self, value): + ffi.lib.LLVMPY_SetModuleName(self, _encode_string(value)) + + @property + def source_file(self): + """ + The module's original source file name + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleSourceFileName(self)) + + @property + def data_layout(self): + """ + This module's data layout specification, as a string. + """ + # LLVMGetDataLayout() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetDataLayout(self, outmsg) + return str(outmsg) + + @data_layout.setter + def data_layout(self, strrep): + ffi.lib.LLVMPY_SetDataLayout(self, + create_string_buffer( + strrep.encode('utf8'))) + + @property + def triple(self): + """ + This module's target "triple" specification, as a string. + """ + # LLVMGetTarget() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetTarget(self, outmsg) + return str(outmsg) + + @triple.setter + def triple(self, strrep): + ffi.lib.LLVMPY_SetTarget(self, + create_string_buffer( + strrep.encode('utf8'))) + + def link_in(self, other, preserve=False): + """ + Link the *other* module into this one. The *other* module will + be destroyed unless *preserve* is true. + """ + if preserve: + other = other.clone() + link_modules(self, other) + + @property + def global_variables(self): + """ + Return an iterator over this module's global variables. + The iterator will yield a ValueRef for each global variable. + + Note that global variables don't include functions + (a function is a "global value" but not a "global variable" in + LLVM parlance) + """ + it = ffi.lib.LLVMPY_ModuleGlobalsIter(self) + return _GlobalsIterator(it, dict(module=self)) + + @property + def functions(self): + """ + Return an iterator over this module's functions. + The iterator will yield a ValueRef for each function. + """ + it = ffi.lib.LLVMPY_ModuleFunctionsIter(self) + return _FunctionsIterator(it, dict(module=self)) + + @property + def struct_types(self): + """ + Return an iterator over the struct types defined in + the module. The iterator will yield a TypeRef. + """ + it = ffi.lib.LLVMPY_ModuleTypesIter(self) + return _TypesIterator(it, dict(module=self)) + + def clone(self): + return ModuleRef(ffi.lib.LLVMPY_CloneModule(self), self._context) + + +class _Iterator(ffi.ObjectRef): + + kind = None + + def __init__(self, ptr, parents): + ffi.ObjectRef.__init__(self, ptr) + self._parents = parents + assert self.kind is not None + + def __next__(self): + vp = self._next() + if vp: + return ValueRef(vp, self.kind, self._parents) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _GlobalsIterator(_Iterator): + + kind = 'global' + + def _dispose(self): + self._capi.LLVMPY_DisposeGlobalsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_GlobalsIterNext(self) + + +class _FunctionsIterator(_Iterator): + + kind = 'function' + + def _dispose(self): + self._capi.LLVMPY_DisposeFunctionsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_FunctionsIterNext(self) + + +class _TypesIterator(_Iterator): + + kind = 'type' + + def _dispose(self): + self._capi.LLVMPY_DisposeTypesIter(self) + + def __next__(self): + vp = self._next() + if vp: + return TypeRef(vp) + else: + raise StopIteration + + def _next(self): + return ffi.lib.LLVMPY_TypesIterNext(self) + + next = __next__ + + +# ============================================================================= +# Set function FFI + +ffi.lib.LLVMPY_ParseAssembly.argtypes = [ffi.LLVMContextRef, + c_char_p, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseAssembly.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_ParseBitcode.argtypes = [ffi.LLVMContextRef, + c_char_p, c_size_t, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseBitcode.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_DisposeModule.argtypes = [ffi.LLVMModuleRef] + +ffi.lib.LLVMPY_PrintModuleToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_WriteBitcodeToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p), + POINTER(c_size_t)] + +ffi.lib.LLVMPY_GetNamedFunction.argtypes = [ffi.LLVMModuleRef, + c_char_p] +ffi.lib.LLVMPY_GetNamedFunction.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_VerifyModule.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_VerifyModule.restype = c_bool + +ffi.lib.LLVMPY_GetDataLayout.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetDataLayout.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetTarget.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetTarget.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetNamedGlobalVariable.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedGlobalVariable.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_GetNamedStructType.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedStructType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_ModuleGlobalsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleGlobalsIter.restype = ffi.LLVMGlobalsIterator + +ffi.lib.LLVMPY_DisposeGlobalsIter.argtypes = [ffi.LLVMGlobalsIterator] + +ffi.lib.LLVMPY_GlobalsIterNext.argtypes = [ffi.LLVMGlobalsIterator] +ffi.lib.LLVMPY_GlobalsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_ModuleFunctionsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleFunctionsIter.restype = ffi.LLVMFunctionsIterator + +ffi.lib.LLVMPY_ModuleTypesIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleTypesIter.restype = ffi.LLVMTypesIterator + +ffi.lib.LLVMPY_DisposeFunctionsIter.argtypes = [ffi.LLVMFunctionsIterator] + +ffi.lib.LLVMPY_DisposeTypesIter.argtypes = [ffi.LLVMTypesIterator] + +ffi.lib.LLVMPY_FunctionsIterNext.argtypes = [ffi.LLVMFunctionsIterator] +ffi.lib.LLVMPY_FunctionsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_TypesIterNext.argtypes = [ffi.LLVMTypesIterator] +ffi.lib.LLVMPY_TypesIterNext.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_CloneModule.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_CloneModule.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_GetModuleName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleName.restype = c_char_p + +ffi.lib.LLVMPY_SetModuleName.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetModuleSourceFileName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleSourceFileName.restype = c_char_p diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/newpassmanagers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/newpassmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..00634714b7ffd9f8e44f2732bcf7cd220ef04109 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/newpassmanagers.py @@ -0,0 +1,1049 @@ +from ctypes import c_bool, c_int, c_size_t, POINTER, Structure, byref, c_char_p +from collections import namedtuple +from enum import IntFlag +from llvmlite.binding import ffi + + +def create_new_module_pass_manager(): + return ModulePassManager() + + +def create_new_function_pass_manager(): + return FunctionPassManager() + + +def create_pass_builder(tm, pto): + return PassBuilder(tm, pto) + + +def create_pipeline_tuning_options(speed_level=2, size_level=0): + return PipelineTuningOptions(speed_level, size_level) + + +_prunestats = namedtuple('PruneStats', + ('basicblock diamond fanout fanout_raise')) + + +class PruneStats(_prunestats): + """ Holds statistics from reference count pruning. + """ + + def __add__(self, other): + if not isinstance(other, PruneStats): + msg = 'PruneStats can only be added to another PruneStats, got {}.' + raise TypeError(msg.format(type(other))) + return PruneStats(self.basicblock + other.basicblock, + self.diamond + other.diamond, + self.fanout + other.fanout, + self.fanout_raise + other.fanout_raise) + + def __sub__(self, other): + if not isinstance(other, PruneStats): + msg = ('PruneStats can only be subtracted from another PruneStats, ' + 'got {}.') + raise TypeError(msg.format(type(other))) + return PruneStats(self.basicblock - other.basicblock, + self.diamond - other.diamond, + self.fanout - other.fanout, + self.fanout_raise - other.fanout_raise) + + +class _c_PruneStats(Structure): + _fields_ = [ + ('basicblock', c_size_t), + ('diamond', c_size_t), + ('fanout', c_size_t), + ('fanout_raise', c_size_t)] + + +def dump_refprune_stats(printout=False): + """ Returns a namedtuple containing the current values for the refop pruning + statistics. If kwarg `printout` is True the stats are printed to stderr, + default is False. + """ + + stats = _c_PruneStats(0, 0, 0, 0) + do_print = c_bool(printout) + + ffi.lib.LLVMPY_DumpRefPruneStats(byref(stats), do_print) + return PruneStats(stats.basicblock, stats.diamond, stats.fanout, + stats.fanout_raise) + + +# TODO: Rename and add tests for these +# Although new pass manager has its own timing APIs, we still need to support +# the legacy ones as LLVM backend still used the LegacyPassManager. These APIs +# will be used to time the backend passes such as instruction selection, +# regalloc, etc +def set_time_passes(enable): + """Enable or disable the pass timers. + + Parameters + ---------- + enable : bool + Set to True to enable the pass timers. + Set to False to disable the pass timers. + """ + ffi.lib.LLVMPY_SetTimePasses(c_bool(enable)) + + +def report_and_reset_timings(): + """Returns the pass timings report and resets the LLVM internal timers. + + Pass timers are enabled by ``set_time_passes()``. If the timers are not + enabled, this function will return an empty string. + + Returns + ------- + res : str + LLVM generated timing report. + """ + with ffi.OutputString() as buf: + ffi.lib.LLVMPY_ReportAndResetTimings(buf) + return str(buf) + + +class RefPruneSubpasses(IntFlag): + PER_BB = 0b0001 # noqa: E221 + DIAMOND = 0b0010 # noqa: E221 + FANOUT = 0b0100 # noqa: E221 + FANOUT_RAISE = 0b1000 + ALL = PER_BB | DIAMOND | FANOUT | FANOUT_RAISE + + +class NewPassManager(): + + def __init__(self): + if type(self) is NewPassManager: + raise TypeError("Cannot instantiate NewPassManager directly") + + def run(self,IR, pb): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_RunNewModulePassManager(self, IR, pb) + else: + ffi.lib.LLVMPY_RunNewFunctionPassManager(self, IR, pb) + + def add_aa_eval_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddAAEvaluator(self) + else: + ffi.lib.LLVMPY_function_AddAAEvaluator(self) + + def add_simplify_cfg_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddSimplifyCFGPass(self) + else: + ffi.lib.LLVMPY_function_AddSimplifyCFGPass(self) + + def add_loop_unroll_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLoopUnrollPass(self) + else: + ffi.lib.LLVMPY_function_AddLoopUnrollPass(self) + + def add_instruction_combine_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddInstCombinePass(self) + else: + ffi.lib.LLVMPY_function_AddInstCombinePass(self) + + def add_jump_threading_pass(self, threshold=-1): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_AddJumpThreadingPass_module(self, threshold) + else: + ffi.lib.LLVMPY_AddJumpThreadingPass_function(self, threshold) + + def add_cfg_printer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddCFGPrinterPass(self) + else: + ffi.lib.LLVMPY_function_AddCFGPrinterPass(self) + + def add_cfg_only_printer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddCFGOnlyPrinterPass(self) + else: + ffi.lib.LLVMPY_function_AddCFGOnlyPrinterPass(self) + + def add_dom_printer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddDomPrinter(self) + else: + ffi.lib.LLVMPY_function_AddDomPrinter(self) + + def add_dom_only_printer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddDomOnlyPrinter(self) + else: + ffi.lib.LLVMPY_function_AddDomOnlyPrinter(self) + + def add_post_dom_printer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddPostDomPrinter(self) + else: + ffi.lib.LLVMPY_function_AddPostDomPrinter(self) + + def add_post_dom_only_printer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddPostDomOnlyPrinter(self) + else: + ffi.lib.LLVMPY_function_AddPostDomOnlyPrinter(self) + + def add_dom_viewer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddDomViewer(self) + else: + ffi.lib.LLVMPY_function_AddDomViewer(self) + + def add_dom_only_viewer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddDomOnlyViewer(self) + else: + ffi.lib.LLVMPY_function_AddDomOnlyViewer(self) + + def add_post_dom_viewer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddPostDomViewer(self) + else: + ffi.lib.LLVMPY_function_AddPostDomViewer(self) + + def add_post_dom_only_viewer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddPostDomOnlyViewer(self) + else: + ffi.lib.LLVMPY_function_AddPostDomOnlyViewer(self) + + def add_lint_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLintPass(self) + else: + ffi.lib.LLVMPY_function_AddLintPass(self) + + def add_aggressive_dce_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddADCEPass(self) + else: + ffi.lib.LLVMPY_function_AddADCEPass(self) + + def add_break_critical_edges_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddBreakCriticalEdgesPass(self) + else: + ffi.lib.LLVMPY_function_AddBreakCriticalEdgesPass(self) + + def add_dead_store_elimination_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddDSEPass(self) + else: + ffi.lib.LLVMPY_function_AddDSEPass(self) + + def add_dead_code_elimination_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddDCEPass(self) + else: + ffi.lib.LLVMPY_function_AddDCEPass(self) + + def add_aggressive_instcombine_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddAggressiveInstCombinePass(self) + else: + ffi.lib.LLVMPY_function_AddAggressiveInstCombinePass(self) + + def add_lcssa_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLCSSAPass(self) + else: + ffi.lib.LLVMPY_function_AddLCSSAPass(self) + + def add_new_gvn_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddNewGVNPass(self) + else: + ffi.lib.LLVMPY_function_AddNewGVNPass(self) + + def add_loop_simplify_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLoopSimplifyPass(self) + else: + ffi.lib.LLVMPY_function_AddLoopSimplifyPass(self) + + def add_loop_unroll_and_jam_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLoopUnrollAndJamPass(self) + else: + ffi.lib.LLVMPY_function_AddLoopUnrollAndJamPass(self) + + def add_sccp_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddSCCPPass(self) + else: + ffi.lib.LLVMPY_function_AddSCCPPass(self) + + def add_lower_atomic_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLowerAtomicPass(self) + else: + ffi.lib.LLVMPY_function_AddLowerAtomicPass(self) + + def add_lower_invoke_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLowerInvokePass(self) + else: + ffi.lib.LLVMPY_function_AddLowerInvokePass(self) + + def add_lower_switch_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLowerSwitchPass(self) + else: + ffi.lib.LLVMPY_function_AddLowerSwitchPass(self) + + def add_mem_copy_opt_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddMemCpyOptPass(self) + else: + ffi.lib.LLVMPY_function_AddMemCpyOptPass(self) + + def add_unify_function_exit_nodes_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddUnifyFunctionExitNodesPass(self) + else: + ffi.lib.LLVMPY_function_AddUnifyFunctionExitNodesPass(self) + + def add_reassociate_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddReassociatePass(self) + else: + ffi.lib.LLVMPY_function_AddReassociatePass(self) + + def add_register_to_memory_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddRegToMemPass(self) + else: + ffi.lib.LLVMPY_function_AddRegToMemPass(self) + + def add_sroa_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddSROAPass(self) + else: + ffi.lib.LLVMPY_function_AddSROAPass(self) + + def add_sinking_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddSinkingPass(self) + else: + ffi.lib.LLVMPY_function_AddSinkingPass(self) + + def add_tail_call_elimination_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddTailCallElimPass(self) + else: + ffi.lib.LLVMPY_function_AddTailCallElimPass(self) + + def add_instruction_namer_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddInstructionNamerPass(self) + else: + ffi.lib.LLVMPY_function_AddInstructionNamerPass(self) + + def add_loop_deletion_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLoopDeletionPass(self) + else: + ffi.lib.LLVMPY_function_AddLoopDeletionPass(self) + + def add_loop_strength_reduce_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLoopStrengthReducePass(self) + else: + ffi.lib.LLVMPY_function_AddLoopStrengthReducePass(self) + + def add_loop_rotate_pass(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_module_AddLoopRotatePass(self) + else: + ffi.lib.LLVMPY_function_AddLoopRotatePass(self) + + def _dispose(self): + if isinstance(self, ModulePassManager): + ffi.lib.LLVMPY_DisposeNewModulePassManger(self) + else: + ffi.lib.LLVMPY_DisposeNewFunctionPassManger(self) + + +class ModulePassManager(ffi.ObjectRef, NewPassManager): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreateNewModulePassManager() + super().__init__(ptr) + + def add_verifier(self): + ffi.lib.LLVMPY_module_AddVerifierPass(self) + + def add_constant_merge_pass(self): + ffi.lib.LLVMPY_module_AddConstantMergePass(self) + + def add_dead_arg_elimination_pass(self): + ffi.lib.LLVMPY_module_AddDeadArgumentEliminationPass(self) + + def add_dot_call_graph_printer_pass(self): + ffi.lib.LLVMPY_module_AddCallGraphDOTPrinterPass(self) + + # TODO: There are a lot more printer passes in llvm that can be exposed + # FIXME: Find a way to write the output to a buffer instead of stdout + def add_module_debug_info_pass(self): + ffi.lib.LLVMPY_module_AddModuleDebugInfoPrinterPass(self) + + def add_always_inliner_pass(self): + ffi.lib.LLVMPY_module_AddAlwaysInlinerPass(self) + + def add_rpo_function_attrs_pass(self): + ffi.lib.LLVMPY_module_AddReversePostOrderFunctionAttrsPass(self) + + def add_global_dead_code_eliminate_pass(self): + ffi.lib.LLVMPY_module_AddGlobalDCEPass(self) + + def add_global_opt_pass(self): + ffi.lib.LLVMPY_module_AddGlobalOptPass(self) + + def add_ipsccp_pass(self): + ffi.lib.LLVMPY_module_AddIPSCCPPass(self) + + def add_internalize_pass(self): + ffi.lib.LLVMPY_module_AddInternalizePass(self) + + def add_loop_extract_pass(self): + ffi.lib.LLVMPY_module_AddLoopExtractorPass(self) + + def add_merge_functions_pass(self): + ffi.lib.LLVMPY_module_AddMergeFunctionsPass(self) + + def add_partial_inliner_pass(self): + ffi.lib.LLVMPY_module_AddPartialInlinerPass(self) + + def add_strip_symbols_pass(self): + ffi.lib.LLVMPY_module_AddStripSymbolsPass(self) + + def add_strip_dead_debug_info_pass(self): + ffi.lib.LLVMPY_module_AddStripDeadDebugInfoPass(self) + + def add_strip_dead_prototype_pass(self): + ffi.lib.LLVMPY_module_AddStripDeadPrototypesPass(self) + + def add_strip_debug_declare_pass(self): + ffi.lib.LLVMPY_module_AddStripDebugDeclarePass(self) + + def add_strip_non_debug_symbols_pass(self): + ffi.lib.LLVMPY_module_AddStripNonDebugSymbolsPass(self) + + def add_argument_promotion_pass(self): + ffi.lib.LLVMPY_module_AddArgumentPromotionPass(self) + + def add_post_order_function_attributes_pass(self): + ffi.lib.LLVMPY_module_AddPostOrderFunctionAttrsPass(self) + + # Non-standard LLVM passes + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddRefPrunePass_module(self, iflags, subgraph_limit) + + +class FunctionPassManager(ffi.ObjectRef, NewPassManager): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreateNewFunctionPassManager() + super().__init__(ptr) + + # Non-standard LLVM passes + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddRefPrunePass_function(self, iflags, subgraph_limit) + + +class PipelineTuningOptions(ffi.ObjectRef): + + def __init__(self, speed_level=2, size_level=0): + self._speed_level = None + self._size_level = None + self.speed_level = speed_level + self.size_level = size_level + super().__init__(ffi.lib.LLVMPY_CreatePipelineTuningOptions()) + + @property + def speed_level(self): + return self._speed_level + + @speed_level.setter + def speed_level(self, value): + if not 0 <= value <= 3: + raise ValueError( + "Optimization level for speed should be 0, 1, 2, or 3") + self._speed_level = value + + @property + def size_level(self): + return self._size_level + + @size_level.setter + def size_level(self, value): + if not 0 <= value <= 2: + raise ValueError("Optimization level for size should be 0, 1, or 2") + if value != 0 and self.speed_level != 2: + raise ValueError( + "Optimization for size should be encoded with speed level == 2") + self._size_level = value + + @property + def loop_interleaving(self): + return ffi.lib.LLVMPY_PTOGetLoopInterleaving(self) + + @loop_interleaving.setter + def loop_interleaving(self, value): + ffi.lib.LLVMPY_PTOSetLoopInterleaving(self, value) + + @property + def loop_vectorization(self): + return ffi.lib.LLVMPY_PTOGetLoopVectorization(self) + + @loop_vectorization.setter + def loop_vectorization(self, value): + ffi.lib.LLVMPY_PTOSetLoopVectorization(self, value) + + @property + def slp_vectorization(self): + return ffi.lib.LLVMPY_PTOGetSLPVectorization(self) + + @slp_vectorization.setter + def slp_vectorization(self, value): + ffi.lib.LLVMPY_PTOSetSLPVectorization(self, value) + + @property + def loop_unrolling(self): + return ffi.lib.LLVMPY_PTOGetLoopUnrolling(self) + + @loop_unrolling.setter + def loop_unrolling(self, value): + ffi.lib.LLVMPY_PTOSetLoopUnrolling(self, value) + + @property + def inlining_threshold(self): + return ffi.lib.LLVMPY_PTOGetInlinerThreshold(self) + + @inlining_threshold.setter + def inlining_threshold(self, value): + ffi.lib.LLVMPY_PTOSetInlinerThreshold(self, value) + + def _dispose(self): + ffi.lib.LLVMPY_DisposePipelineTuningOptions(self) + + +class TimePassesHandler(ffi.ObjectRef): + def __init__(self): + super().__init__(ffi.lib.LLVMPY_CreateTimePassesHandler()) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeTimePassesHandler(self) + + +class PassBuilder(ffi.ObjectRef): + + def __init__(self, tm, pto): + super().__init__(ffi.lib.LLVMPY_CreatePassBuilder(tm, pto)) + self._pto = pto + self._tm = tm + self._time_passes_handler = None + + def getModulePassManager(self): + return ModulePassManager( + ffi.lib.LLVMPY_buildPerModuleDefaultPipeline( + self, self._pto.speed_level, self._pto.size_level) + ) + + def getFunctionPassManager(self): + return FunctionPassManager( + ffi.lib.LLVMPY_buildFunctionSimplificationPipeline( + self, self._pto.speed_level, self._pto.size_level) + ) + + def start_pass_timing(self): + """Enable the pass timers. + + Raises + ------ + RuntimeError + If pass timing is already enabled. + """ + if self._time_passes_handler: + raise RuntimeError("Pass timing can only be done once") + self._time_passes_handler = TimePassesHandler() + ffi.lib.LLVMPY_EnableTimePasses(self, self._time_passes_handler) + + def finish_pass_timing(self): + """Returns the pass timings report and disables the LLVM internal + timers. Pass timers are enabled by ``start_pass_timing()``. If the + timers are not enabled, this function will return an empty string. + + Returns + ------- + res : str + LLVM generated timing report. + """ + + if not self._time_passes_handler: + raise RuntimeError("Pass timing is not enabled") + + with ffi.OutputString() as buf: + ffi.lib.LLVMPY_ReportAndDisableTimePasses( + self._time_passes_handler, buf) + return str(buf) + + def _dispose(self): + ffi.lib.LLVMPY_DisposePassBuilder(self) + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_DumpRefPruneStats.argtypes = [POINTER(_c_PruneStats), c_bool] + +ffi.lib.LLVMPY_SetTimePasses.argtypes = [c_bool] + +ffi.lib.LLVMPY_ReportAndResetTimings.argtypes = [POINTER(c_char_p)] + +# ModulePassManager + +ffi.lib.LLVMPY_CreateNewModulePassManager.restype = ffi.LLVMModulePassManagerRef + +ffi.lib.LLVMPY_RunNewModulePassManager.argtypes = [ + ffi.LLVMModulePassManagerRef, ffi.LLVMModuleRef, + ffi.LLVMPassBuilderRef,] + +ffi.lib.LLVMPY_module_AddVerifierPass.argtypes = [ffi.LLVMModulePassManagerRef,] +ffi.lib.LLVMPY_module_AddAAEvaluator.argtypes = [ffi.LLVMModulePassManagerRef,] +ffi.lib.LLVMPY_module_AddSimplifyCFGPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLoopUnrollPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLoopRotatePass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddInstCombinePass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddJumpThreadingPass_module.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddCFGPrinterPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddCFGOnlyPrinterPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddDomPrinter.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddDomOnlyPrinter.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddPostDomPrinter.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddPostDomOnlyPrinter.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddDomViewer.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddDomOnlyViewer.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddPostDomViewer.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddPostDomOnlyViewer.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLintPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddADCEPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddBreakCriticalEdgesPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddDSEPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddDCEPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddAggressiveInstCombinePass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLCSSAPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddNewGVNPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLoopSimplifyPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLoopUnrollAndJamPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddSCCPPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLowerAtomicPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLowerInvokePass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLowerSwitchPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddMemCpyOptPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddUnifyFunctionExitNodesPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddReassociatePass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddRegToMemPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddSROAPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddSinkingPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddTailCallElimPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddInstructionNamerPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLoopDeletionPass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddLoopStrengthReducePass.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_module_AddConstantMergePass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddDeadArgumentEliminationPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddCallGraphDOTPrinterPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddModuleDebugInfoPrinterPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddAlwaysInlinerPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddReversePostOrderFunctionAttrsPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddGlobalDCEPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddGlobalOptPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddIPSCCPPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddInternalizePass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddLoopExtractorPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddMergeFunctionsPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddPartialInlinerPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddStripSymbolsPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddStripDeadDebugInfoPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddStripDeadPrototypesPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddStripDebugDeclarePass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddStripNonDebugSymbolsPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddArgumentPromotionPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_module_AddPostOrderFunctionAttrsPass.argtypes = [ + ffi.LLVMModulePassManagerRef, ] + +ffi.lib.LLVMPY_DisposeNewModulePassManger.argtypes = [ + ffi.LLVMModulePassManagerRef,] + +ffi.lib.LLVMPY_AddRefPrunePass_module.argtypes = [ + ffi.LLVMModulePassManagerRef, c_int, c_size_t, +] + +# FunctionPassManager + +ffi.lib.LLVMPY_CreateNewFunctionPassManager.restype = \ + ffi.LLVMFunctionPassManagerRef + +ffi.lib.LLVMPY_RunNewFunctionPassManager.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ffi.LLVMValueRef, + ffi.LLVMPassBuilderRef,] + +ffi.lib.LLVMPY_function_AddAAEvaluator.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_function_AddSimplifyCFGPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_function_AddLoopUnrollPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_function_AddInstCombinePass.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddJumpThreadingPass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef, c_int,] + +ffi.lib.LLVMPY_function_AddCFGPrinterPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddCFGOnlyPrinterPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddDomPrinter.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddDomOnlyPrinter.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddPostDomPrinter.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddPostDomOnlyPrinter.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddDomViewer.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddDomOnlyViewer.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddPostDomViewer.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddPostDomOnlyViewer.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLintPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddADCEPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddBreakCriticalEdgesPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddDSEPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddDCEPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddAggressiveInstCombinePass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLCSSAPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddNewGVNPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLoopSimplifyPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLoopUnrollAndJamPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddSCCPPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLowerAtomicPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLowerInvokePass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLowerSwitchPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddMemCpyOptPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddUnifyFunctionExitNodesPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddReassociatePass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddRegToMemPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddSROAPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddSinkingPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddTailCallElimPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddInstructionNamerPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLoopRotatePass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLoopDeletionPass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_function_AddLoopStrengthReducePass.argtypes = [ + ffi.LLVMFunctionPassManagerRef, ] + +ffi.lib.LLVMPY_DisposeNewFunctionPassManger.argtypes = [ + ffi.LLVMFunctionPassManagerRef,] + +ffi.lib.LLVMPY_AddRefPrunePass_function.argtypes = [ + ffi.LLVMFunctionPassManagerRef, c_int, c_size_t, +] + +# PipelineTuningOptions + +ffi.lib.LLVMPY_CreatePipelineTuningOptions.restype = \ + ffi.LLVMPipelineTuningOptionsRef + +ffi.lib.LLVMPY_PTOGetLoopInterleaving.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopInterleaving.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopInterleaving.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetLoopVectorization.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetSLPVectorization.restype = c_bool +ffi.lib.LLVMPY_PTOGetSLPVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetSLPVectorization.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetLoopUnrolling.restype = c_bool +ffi.lib.LLVMPY_PTOGetLoopUnrolling.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef,] + +ffi.lib.LLVMPY_PTOSetLoopUnrolling.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_bool] + +ffi.lib.LLVMPY_PTOGetInlinerThreshold.restype = c_int + +ffi.lib.LLVMPY_PTOSetInlinerThreshold.argtypes = [ + ffi.LLVMPipelineTuningOptionsRef, c_int] + +ffi.lib.LLVMPY_DisposePipelineTuningOptions.argtypes = \ + [ffi.LLVMPipelineTuningOptionsRef,] + +# PassBuilder + +ffi.lib.LLVMPY_CreatePassBuilder.restype = ffi.LLVMPassBuilderRef +ffi.lib.LLVMPY_CreatePassBuilder.argtypes = [ + ffi.LLVMTargetMachineRef, + ffi.LLVMPipelineTuningOptionsRef, +] + +ffi.lib.LLVMPY_DisposePassBuilder.argtypes = [ffi.LLVMPassBuilderRef,] + +ffi.lib.LLVMPY_CreateTimePassesHandler.restype = \ + ffi.LLVMTimePassesHandlerRef + +ffi.lib.LLVMPY_DisposeTimePassesHandler.argtypes = [ + ffi.LLVMTimePassesHandlerRef,] + +ffi.lib.LLVMPY_EnableTimePasses.argtypes = [ + ffi.LLVMPassBuilderRef, + ffi.LLVMTimePassesHandlerRef, +] + +ffi.lib.LLVMPY_ReportAndDisableTimePasses.argtypes = [ + ffi.LLVMTimePassesHandlerRef, + POINTER(c_char_p), +] + +# Pipeline builders + +ffi.lib.LLVMPY_buildPerModuleDefaultPipeline.restype = \ + ffi.LLVMModulePassManagerRef + +ffi.lib.LLVMPY_buildPerModuleDefaultPipeline.argtypes = [ + ffi.LLVMPassBuilderRef, c_int, c_int] + +ffi.lib.LLVMPY_buildFunctionSimplificationPipeline.restype = \ + ffi.LLVMFunctionPassManagerRef + +ffi.lib.LLVMPY_buildFunctionSimplificationPipeline.argtypes = [ + ffi.LLVMPassBuilderRef, c_int, c_int] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/object_file.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/object_file.py new file mode 100644 index 0000000000000000000000000000000000000000..e5961b079ef87393347436a8fd8e70fb0525b39d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/object_file.py @@ -0,0 +1,82 @@ +from llvmlite.binding import ffi +from ctypes import (c_bool, c_char_p, c_char, c_size_t, string_at, c_uint64, + POINTER) + + +class SectionIteratorRef(ffi.ObjectRef): + def name(self): + return ffi.lib.LLVMPY_GetSectionName(self) + + def is_text(self): + return ffi.lib.LLVMPY_IsSectionText(self) + + def size(self): + return ffi.lib.LLVMPY_GetSectionSize(self) + + def address(self): + return ffi.lib.LLVMPY_GetSectionAddress(self) + + def data(self): + return string_at(ffi.lib.LLVMPY_GetSectionContents(self), self.size()) + + def is_end(self, object_file): + return ffi.lib.LLVMPY_IsSectionIteratorAtEnd(object_file, self) + + def next(self): + ffi.lib.LLVMPY_MoveToNextSection(self) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeSectionIterator(self) + + +class ObjectFileRef(ffi.ObjectRef): + @classmethod + def from_data(cls, data): + return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data))) + + @classmethod + def from_path(cls, path): + with open(path, 'rb') as f: + data = f.read() + return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data))) + + def sections(self): + it = SectionIteratorRef(ffi.lib.LLVMPY_GetSections(self)) + while not it.is_end(self): + yield it + it.next() + + def _dispose(self): + ffi.lib.LLVMPY_DisposeObjectFile(self) + + +ffi.lib.LLVMPY_CreateObjectFile.argtypes = [c_char_p, c_size_t] +ffi.lib.LLVMPY_CreateObjectFile.restype = ffi.LLVMObjectFileRef + +ffi.lib.LLVMPY_DisposeObjectFile.argtypes = [ffi.LLVMObjectFileRef] + +ffi.lib.LLVMPY_GetSections.argtypes = [ffi.LLVMObjectFileRef] +ffi.lib.LLVMPY_GetSections.restype = ffi.LLVMSectionIteratorRef + +ffi.lib.LLVMPY_DisposeSectionIterator.argtypes = [ffi.LLVMSectionIteratorRef] + +ffi.lib.LLVMPY_MoveToNextSection.argtypes = [ffi.LLVMSectionIteratorRef] + +ffi.lib.LLVMPY_IsSectionIteratorAtEnd.argtypes = [ + ffi.LLVMObjectFileRef, ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_IsSectionIteratorAtEnd.restype = c_bool + +ffi.lib.LLVMPY_GetSectionName.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionName.restype = c_char_p + +ffi.lib.LLVMPY_GetSectionSize.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionSize.restype = c_uint64 + +ffi.lib.LLVMPY_GetSectionAddress.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionAddress.restype = c_uint64 + +ffi.lib.LLVMPY_GetSectionContents.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionContents.restype = POINTER(c_char) + +ffi.lib.LLVMPY_IsSectionText.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_IsSectionText.restype = c_bool diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/options.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/options.py new file mode 100644 index 0000000000000000000000000000000000000000..15eedfaaf476938c97abcd7e75131e9590f34203 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/options.py @@ -0,0 +1,17 @@ +from llvmlite.binding import ffi +from llvmlite.binding.common import _encode_string +from ctypes import c_char_p + + +def set_option(name, option): + """ + Set the given LLVM "command-line" option. + + For example set_option("test", "-debug-pass=Structure") would display + all optimization passes when generating code. + """ + ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), + _encode_string(option)) + + +ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/orcjit.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/orcjit.py new file mode 100644 index 0000000000000000000000000000000000000000..82996f586bf688bce389db15d29b0c294f5cba67 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/orcjit.py @@ -0,0 +1,342 @@ +import ctypes +from ctypes import POINTER, c_bool, c_char_p, c_uint8, c_uint64, c_size_t + +from llvmlite.binding import ffi, targets + + +class _LinkElement(ctypes.Structure): + _fields_ = [("element_kind", c_uint8), + ("value", c_char_p), + ("value_len", c_size_t)] + + +class _SymbolAddress(ctypes.Structure): + _fields_ = [("name", c_char_p), ("address", c_uint64)] + + +class JITLibraryBuilder: + """ + Create a library for linking by OrcJIT + + OrcJIT operates like a linker: a number of compilation units and + dependencies are collected together and linked into a single dynamic library + that can export functions to other libraries or to be consumed directly as + entry points into JITted code. The native OrcJIT has a lot of memory + management complications so this API is designed to work well with Python's + garbage collection. + + The creation of a new library is a bit like a linker command line where + compilation units, mostly as LLVM IR, and previously constructed libraries + are linked together, then loaded into memory, and the addresses of exported + symbols are extracted. Any static initializers are run and the exported + addresses and a resource tracker is produced. As long as the resource + tracker is referenced somewhere in Python, the exported addresses will be + valid. Once the resource tracker is garbage collected, the static + destructors will run and library will be unloaded from memory. + """ + def __init__(self): + self.__entries = [] + self.__exports = set() + self.__imports = {} + + def add_ir(self, llvmir): + """ + Adds a compilation unit to the library using LLVM IR as the input + format. + + This takes a string or an object that can be converted to a string, + including IRBuilder, that contains LLVM IR. + """ + self.__entries.append((0, str(llvmir).encode('utf-8'))) + return self + + def add_native_assembly(self, asm): + """ + Adds a compilation unit to the library using native assembly as the + input format. + + This takes a string or an object that can be converted to a string that + contains native assembly, which will be + parsed by LLVM. + """ + self.__entries.append((1, str(asm).encode('utf-8'))) + return self + + def add_object_img(self, data): + """ + Adds a compilation unit to the library using pre-compiled object code. + + This takes the bytes of the contents of an object artifact which will be + loaded by LLVM. + """ + self.__entries.append((2, bytes(data))) + return self + + def add_object_file(self, file_path): + """ + Adds a compilation unit to the library using pre-compiled object file. + + This takes a string or path-like object that references an object file + which will be loaded by LLVM. + """ + with open(file_path, "rb") as f: + self.__entries.append((2, f.read())) + return self + + def add_jit_library(self, name): + """ + Adds an existing JIT library as prerequisite. + + The name of the library must match the one provided in a previous link + command. + """ + self.__entries.append((3, str(name).encode('utf-8'))) + return self + + def add_current_process(self): + """ + Allows the JITted library to access symbols in the current binary. + + That is, it allows exporting the current binary's symbols, including + loaded libraries, as imports to the JITted + library. + """ + self.__entries.append((3, b'')) + return self + + def import_symbol(self, name, address): + """ + Register the *address* of global symbol *name*. This will make + it usable (e.g. callable) from LLVM-compiled functions. + """ + self.__imports[str(name)] = c_uint64(address) + return self + + def export_symbol(self, name): + """ + During linking, extract the address of a symbol that was defined in one + of the compilation units. + + This allows getting symbols, functions or global variables, out of the + JIT linked library. The addresses will be + available when the link method is called. + """ + self.__exports.add(str(name)) + return self + + def link(self, lljit, library_name): + """ + Link all the current compilation units into a JITted library and extract + the address of exported symbols. + + An instance of the OrcJIT instance must be provided and this will be the + scope that is used to find other JITted libraries that are dependencies + and also be the place where this library will be defined. + + After linking, the method will return a resource tracker that keeps the + library alive. This tracker also knows the addresses of any exported + symbols that were requested. + + The addresses will be valid as long as the resource tracker is + referenced. + + When the resource tracker is destroyed, the library will be cleaned up, + however, the name of the library cannot be reused. + """ + assert not lljit.closed, "Cannot add to closed JIT" + encoded_library_name = str(library_name).encode('utf-8') + assert len(encoded_library_name) > 0, "Library cannot be empty" + elements = (_LinkElement * len(self.__entries))() + for idx, (kind, value) in enumerate(self.__entries): + elements[idx].element_kind = c_uint8(kind) + elements[idx].value = c_char_p(value) + elements[idx].value_len = c_size_t(len(value)) + exports = (_SymbolAddress * len(self.__exports))() + for idx, name in enumerate(self.__exports): + exports[idx].name = name.encode('utf-8') + + imports = (_SymbolAddress * len(self.__imports))() + for idx, (name, addr) in enumerate(self.__imports.items()): + imports[idx].name = name.encode('utf-8') + imports[idx].address = addr + + with ffi.OutputString() as outerr: + tracker = lljit._capi.LLVMPY_LLJIT_Link( + lljit._ptr, + encoded_library_name, + elements, + len(self.__entries), + imports, + len(self.__imports), + exports, + len(self.__exports), + outerr) + if not tracker: + raise RuntimeError(str(outerr)) + return ResourceTracker(tracker, + library_name, + {name: exports[idx].address + for idx, name in enumerate(self.__exports)}) + + +class ResourceTracker(ffi.ObjectRef): + """ + A resource tracker is created for each loaded JIT library and keeps the + module alive. + + OrcJIT supports unloading libraries that are no longer used. This resource + tracker should be stored in any object that reference functions or constants + for a JITted library. When all references to the resource tracker are + dropped, this will trigger LLVM to unload the library and destroy any + functions. + + Failure to keep resource trackers while calling a function or accessing a + symbol can result in crashes or memory corruption. + + LLVM internally tracks references between different libraries, so only + "leaf" libraries need to be tracked. + """ + def __init__(self, ptr, name, addresses): + self.__addresses = addresses + self.__name = name + ffi.ObjectRef.__init__(self, ptr) + + def __getitem__(self, item): + """ + Get the address of an exported symbol as an integer + """ + return self.__addresses[item] + + @property + def name(self): + return self.__name + + def _dispose(self): + with ffi.OutputString() as outerr: + if self._capi.LLVMPY_LLJIT_Dylib_Tracker_Dispose(self, outerr): + raise RuntimeError(str(outerr)) + + +class LLJIT(ffi.ObjectRef): + """ + A OrcJIT-based LLVM JIT engine that can compile and run LLVM IR as a + collection of JITted dynamic libraries + + The C++ OrcJIT API has a lot of memory ownership patterns that do not work + with Python. This API attempts to provide ones that are safe at the expense + of some features. Each LLJIT instance is a collection of JIT-compiled + libraries. In the C++ API, there is a "main" library; this API does not + provide access to the main library. Use the JITLibraryBuilder to create a + new named library instead. + """ + def __init__(self, ptr): + self._td = None + ffi.ObjectRef.__init__(self, ptr) + + def lookup(self, dylib, fn): + """ + Find a function in this dynamic library and construct a new tracking + object for it + + If the library or function do not exist, an exception will occur. + + Parameters + ---------- + dylib : str or None + the name of the library containing the symbol + fn : str + the name of the function to get + """ + assert not self.closed, "Cannot lookup in closed JIT" + address = ctypes.c_uint64() + with ffi.OutputString() as outerr: + tracker = ffi.lib.LLVMPY_LLJITLookup(self, + dylib.encode("utf-8"), + fn.encode("utf-8"), + ctypes.byref(address), + outerr) + if not tracker: + raise RuntimeError(str(outerr)) + + return ResourceTracker(tracker, dylib, {fn: address.value}) + + @property + def target_data(self): + """ + The TargetData for this LLJIT instance. + """ + if self._td is not None: + return self._td + ptr = ffi.lib.LLVMPY_LLJITGetDataLayout(self) + self._td = targets.TargetData(ptr) + self._td._owned = True + return self._td + + def _dispose(self): + if self._td is not None: + self._td.detach() + self._capi.LLVMPY_LLJITDispose(self) + + +def create_lljit_compiler(target_machine=None, *, + use_jit_link=False, + suppress_errors=False): + """ + Create an LLJIT instance + """ + with ffi.OutputString() as outerr: + lljit = ffi.lib.LLVMPY_CreateLLJITCompiler(target_machine, + suppress_errors, + use_jit_link, + outerr) + if not lljit: + raise RuntimeError(str(outerr)) + + return LLJIT(lljit) + + +ffi.lib.LLVMPY_LLJITLookup.argtypes = [ + ffi.LLVMOrcLLJITRef, + c_char_p, + c_char_p, + POINTER(c_uint64), + POINTER(c_char_p), +] +ffi.lib.LLVMPY_LLJITLookup.restype = ffi.LLVMOrcDylibTrackerRef + +ffi.lib.LLVMPY_LLJITGetDataLayout.argtypes = [ + ffi.LLVMOrcLLJITRef, +] +ffi.lib.LLVMPY_LLJITGetDataLayout.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_CreateLLJITCompiler.argtypes = [ + ffi.LLVMTargetMachineRef, + c_bool, + c_bool, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_CreateLLJITCompiler.restype = ffi.LLVMOrcLLJITRef + +ffi.lib.LLVMPY_LLJITDispose.argtypes = [ + ffi.LLVMOrcLLJITRef, +] + + +ffi.lib.LLVMPY_LLJIT_Link.argtypes = [ + ffi.LLVMOrcLLJITRef, + c_char_p, + POINTER(_LinkElement), + c_size_t, + POINTER(_SymbolAddress), + c_size_t, + POINTER(_SymbolAddress), + c_size_t, + POINTER(c_char_p) +] +ffi.lib.LLVMPY_LLJIT_Link.restype = ffi.LLVMOrcDylibTrackerRef + +ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.argtypes = [ + ffi.LLVMOrcDylibTrackerRef, + POINTER(c_char_p) +] +ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.restype = c_bool diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/targets.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/targets.py new file mode 100644 index 0000000000000000000000000000000000000000..e9bee114fb23752c059d88d89f875e9bc7251572 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/targets.py @@ -0,0 +1,462 @@ +import os +from ctypes import (POINTER, c_char_p, c_longlong, c_int, c_size_t, + c_void_p, string_at) + +from llvmlite.binding import ffi +from llvmlite.binding.initfini import llvm_version_info +from llvmlite.binding.common import _decode_string, _encode_string +from collections import namedtuple + +# import for backward compatible API, `has_svml` is now in config module. +from llvmlite.binding.config import _has_svml as has_svml # noqa: F401 + + +Triple = namedtuple('Triple', ['Arch', 'SubArch', 'Vendor', + 'OS', 'Env', 'ObjectFormat']) + + +def get_process_triple(): + """ + Return a target triple suitable for generating code for the current process. + An example when the default triple from ``get_default_triple()`` is not be + suitable is when LLVM is compiled for 32-bit but the process is executing + in 64-bit mode. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetProcessTriple(out) + return str(out) + + +def get_triple_parts(triple: str): + """ + Return a tuple of the parts of the given triple. + """ + with ffi.OutputString() as arch, \ + ffi.OutputString() as vendor, \ + ffi.OutputString() as os, ffi.OutputString() as env: + ffi.lib.LLVMPY_GetTripleParts(triple.encode('utf8'), + arch, vendor, os, env) + arch = str(arch) + subarch = '' + for _str in triple.split('-'): + if _str.startswith(arch): + subarch = _str[len(arch):] + break + return Triple(arch, subarch, str(vendor), str(os), + str(env), get_object_format(triple)) + + +class FeatureMap(dict): + """ + Maps feature name to a boolean indicating the availability of the feature. + Extends ``dict`` to add `.flatten()` method. + """ + + def flatten(self, sort=True): + """ + Args + ---- + sort: bool + Optional. If True, the features are sorted by name; otherwise, + the ordering is unstable between python session due to hash + randomization. Defaults to True. + + Returns a string suitable for use as the ``features`` argument to + ``Target.create_target_machine()``. + + """ + iterator = sorted(self.items()) if sort else iter(self.items()) + flag_map = {True: '+', False: '-'} + return ','.join('{0}{1}'.format(flag_map[v], k) + for k, v in iterator) + + +def get_host_cpu_features(): + """ + Returns a dictionary-like object indicating the CPU features for current + architecture and whether they are enabled for this CPU. The key-value pairs + are the feature name as string and a boolean indicating whether the feature + is available. The returned value is an instance of ``FeatureMap`` class, + which adds a new method ``.flatten()`` for returning a string suitable for + use as the "features" argument to ``Target.create_target_machine()``. + + If LLVM has not implemented this feature or it fails to get the information, + this function will raise a RuntimeError exception. + """ + with ffi.OutputString() as out: + outdict = FeatureMap() + if not ffi.lib.LLVMPY_GetHostCPUFeatures(out): + return outdict + flag_map = {'+': True, '-': False} + content = str(out) + if content: # protect against empty string + for feat in content.split(','): + if feat: # protect against empty feature + outdict[feat[1:]] = flag_map[feat[0]] + return outdict + + +def get_default_triple(): + """ + Return the default target triple LLVM is configured to produce code for. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetDefaultTargetTriple(out) + return str(out) + + +def get_host_cpu_name(): + """ + Get the name of the host's CPU, suitable for using with + :meth:`Target.create_target_machine()`. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetHostCPUName(out) + return str(out) + + +# Adapted from https://github.com/llvm/llvm-project/blob/release/15.x/llvm/include/llvm/ADT/Triple.h#L269 # noqa +llvm_version_major = llvm_version_info[0] + + +_object_formats = { + 0: "Unknown", + 1: "COFF", + 2: "DXContainer", + 3: "ELF", + 4: "GOFF", + 5: "MachO", + 6: "SPIRV", + 7: "Wasm", + 8: "XCOFF", +} + + +def get_object_format(triple=None): + """ + Get the object format for the given *triple* string (or the default + triple if omitted). + A string is returned + """ + if triple is None: + triple = get_default_triple() + res = ffi.lib.LLVMPY_GetTripleObjectFormat(_encode_string(triple)) + return _object_formats[res] + + +def create_target_data(layout): + """ + Create a TargetData instance for the given *layout* string. + """ + return TargetData(ffi.lib.LLVMPY_CreateTargetData(_encode_string(layout))) + + +class TargetData(ffi.ObjectRef): + """ + A TargetData provides structured access to a data layout. + Use :func:`create_target_data` to create instances. + """ + + def __str__(self): + if self._closed: + return "" + with ffi.OutputString() as out: + ffi.lib.LLVMPY_CopyStringRepOfTargetData(self, out) + return str(out) + + def _dispose(self): + self._capi.LLVMPY_DisposeTargetData(self) + + def get_abi_size(self, ty): + """ + Get ABI size of LLVM type *ty*. + """ + return ffi.lib.LLVMPY_ABISizeOfType(self, ty) + + def get_element_offset(self, ty, position): + """ + Get byte offset of type's ty element at the given position + """ + + offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position) + if offset == -1: + raise ValueError("Could not determined offset of {}th " + "element of the type '{}'. Is it a struct" + "type?".format(position, str(ty))) + return offset + + def get_abi_alignment(self, ty): + """ + Get minimum ABI alignment of LLVM type *ty*. + """ + return ffi.lib.LLVMPY_ABIAlignmentOfType(self, ty) + + +RELOC = frozenset(['default', 'static', 'pic', 'dynamicnopic']) +CODEMODEL = frozenset(['default', 'jitdefault', 'small', 'kernel', 'medium', + 'large']) + + +class Target(ffi.ObjectRef): + _triple = '' + + # No _dispose() method since LLVMGetTargetFromTriple() returns a + # persistent object. + + @classmethod + def from_default_triple(cls): + """ + Create a Target instance for the default triple. + """ + triple = get_default_triple() + return cls.from_triple(triple) + + @classmethod + def from_triple(cls, triple): + """ + Create a Target instance for the given triple (a string). + """ + with ffi.OutputString() as outerr: + target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode('utf8'), + outerr) + if not target: + raise RuntimeError(str(outerr)) + target = cls(target) + target._triple = triple + return target + + @property + def name(self): + s = ffi.lib.LLVMPY_GetTargetName(self) + return _decode_string(s) + + @property + def description(self): + s = ffi.lib.LLVMPY_GetTargetDescription(self) + return _decode_string(s) + + @property + def triple(self): + return self._triple + + def __str__(self): + return "".format(self.name, self.description) + + def create_target_machine(self, cpu='', features='', + opt=2, reloc='default', codemodel='jitdefault', + printmc=False, jit=False, abiname=''): + """ + Create a new TargetMachine for this target and the given options. + + Specifying codemodel='default' will result in the use of the "small" + code model. Specifying codemodel='jitdefault' will result in the code + model being picked based on platform bitness (32="small", 64="large"). + + The `printmc` option corresponds to llvm's `-print-machineinstrs`. + + The `jit` option should be set when the target-machine is to be used + in a JIT engine. + + The `abiname` option specifies the ABI. RISC-V targets with hard-float + needs to pass the ABI name to LLVM. + """ + assert 0 <= opt <= 3 + assert reloc in RELOC + assert codemodel in CODEMODEL + triple = self._triple + # MCJIT under Windows only supports ELF objects, see + # http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html + # Note we still want to produce regular COFF files in AOT mode. + if os.name == 'nt' and codemodel == 'jitdefault': + triple += '-elf' + tm = ffi.lib.LLVMPY_CreateTargetMachine(self, + _encode_string(triple), + _encode_string(cpu), + _encode_string(features), + opt, + _encode_string(reloc), + _encode_string(codemodel), + int(printmc), + int(jit), + _encode_string(abiname), + ) + if tm: + return TargetMachine(tm) + else: + raise RuntimeError("Cannot create target machine") + + +class TargetMachine(ffi.ObjectRef): + + def _dispose(self): + self._capi.LLVMPY_DisposeTargetMachine(self) + + def add_analysis_passes(self, pm): + """ + Register analysis passes for this target machine with a pass manager. + """ + ffi.lib.LLVMPY_AddAnalysisPasses(self, pm) + + def set_asm_verbosity(self, verbose): + """ + Set whether this target machine will emit assembly with human-readable + comments describing control flow, debug information, and so on. + """ + ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity(self, verbose) + + def emit_object(self, module): + """ + Represent the module as a code object, suitable for use with + the platform's linker. Returns a byte string. + """ + return self._emit_to_memory(module, use_object=True) + + def emit_assembly(self, module): + """ + Return the raw assembler of the module, as a string. + + llvm.initialize_native_asmprinter() must have been called first. + """ + return _decode_string(self._emit_to_memory(module, use_object=False)) + + def _emit_to_memory(self, module, use_object=False): + """Returns bytes of object code of the module. + + Args + ---- + use_object : bool + Emit object code or (if False) emit assembly code. + """ + with ffi.OutputString() as outerr: + mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module, + int(use_object), + outerr) + if not mb: + raise RuntimeError(str(outerr)) + + bufptr = ffi.lib.LLVMPY_GetBufferStart(mb) + bufsz = ffi.lib.LLVMPY_GetBufferSize(mb) + try: + return string_at(bufptr, bufsz) + finally: + ffi.lib.LLVMPY_DisposeMemoryBuffer(mb) + + @property + def target_data(self): + return TargetData(ffi.lib.LLVMPY_CreateTargetMachineData(self)) + + @property + def triple(self): + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetTargetMachineTriple(self, out) + return str(out) + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_GetProcessTriple.argtypes = [POINTER(c_char_p)] +ffi.lib.LLVMPY_GetTripleParts.argtypes = [c_char_p, POINTER(c_char_p), + POINTER(c_char_p), POINTER(c_char_p), + POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetHostCPUFeatures.argtypes = [POINTER(c_char_p)] +ffi.lib.LLVMPY_GetHostCPUFeatures.restype = c_int + +ffi.lib.LLVMPY_GetDefaultTargetTriple.argtypes = [POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetHostCPUName.argtypes = [POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetTripleObjectFormat.argtypes = [c_char_p] +ffi.lib.LLVMPY_GetTripleObjectFormat.restype = c_int + +ffi.lib.LLVMPY_CreateTargetData.argtypes = [c_char_p] +ffi.lib.LLVMPY_CreateTargetData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_CopyStringRepOfTargetData.argtypes = [ + ffi.LLVMTargetDataRef, + POINTER(c_char_p), +] + +ffi.lib.LLVMPY_DisposeTargetData.argtypes = [ + ffi.LLVMTargetDataRef, +] + +ffi.lib.LLVMPY_ABISizeOfType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABISizeOfType.restype = c_longlong + +ffi.lib.LLVMPY_OffsetOfElement.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef, + c_int] +ffi.lib.LLVMPY_OffsetOfElement.restype = c_longlong + +ffi.lib.LLVMPY_ABIAlignmentOfType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABIAlignmentOfType.restype = c_longlong + +ffi.lib.LLVMPY_GetTargetFromTriple.argtypes = [c_char_p, POINTER(c_char_p)] +ffi.lib.LLVMPY_GetTargetFromTriple.restype = ffi.LLVMTargetRef + +ffi.lib.LLVMPY_GetTargetName.argtypes = [ffi.LLVMTargetRef] +ffi.lib.LLVMPY_GetTargetName.restype = c_char_p + +ffi.lib.LLVMPY_GetTargetDescription.argtypes = [ffi.LLVMTargetRef] +ffi.lib.LLVMPY_GetTargetDescription.restype = c_char_p + +ffi.lib.LLVMPY_CreateTargetMachine.argtypes = [ + ffi.LLVMTargetRef, + # Triple + c_char_p, + # CPU + c_char_p, + # Features + c_char_p, + # OptLevel + c_int, + # Reloc + c_char_p, + # CodeModel + c_char_p, + # PrintMC + c_int, + # JIT + c_int, + # ABIName + c_char_p, +] +ffi.lib.LLVMPY_CreateTargetMachine.restype = ffi.LLVMTargetMachineRef + +ffi.lib.LLVMPY_DisposeTargetMachine.argtypes = [ffi.LLVMTargetMachineRef] + +ffi.lib.LLVMPY_GetTargetMachineTriple.argtypes = [ffi.LLVMTargetMachineRef, + POINTER(c_char_p)] + +ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity.argtypes = [ + ffi.LLVMTargetMachineRef, c_int] + +ffi.lib.LLVMPY_AddAnalysisPasses.argtypes = [ + ffi.LLVMTargetMachineRef, + ffi.LLVMPassManagerRef, +] + +ffi.lib.LLVMPY_TargetMachineEmitToMemory.argtypes = [ + ffi.LLVMTargetMachineRef, + ffi.LLVMModuleRef, + c_int, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_TargetMachineEmitToMemory.restype = ffi.LLVMMemoryBufferRef + +ffi.lib.LLVMPY_GetBufferStart.argtypes = [ffi.LLVMMemoryBufferRef] +ffi.lib.LLVMPY_GetBufferStart.restype = c_void_p + +ffi.lib.LLVMPY_GetBufferSize.argtypes = [ffi.LLVMMemoryBufferRef] +ffi.lib.LLVMPY_GetBufferSize.restype = c_size_t + +ffi.lib.LLVMPY_DisposeMemoryBuffer.argtypes = [ffi.LLVMMemoryBufferRef] + +ffi.lib.LLVMPY_CreateTargetMachineData.argtypes = [ + ffi.LLVMTargetMachineRef, +] +ffi.lib.LLVMPY_CreateTargetMachineData.restype = ffi.LLVMTargetDataRef diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/typeref.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/typeref.py new file mode 100644 index 0000000000000000000000000000000000000000..2394f6204d43d1b498bcc1385173d739b1827661 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/typeref.py @@ -0,0 +1,267 @@ +from ctypes import c_int, c_bool, c_void_p, c_uint64, c_uint, POINTER +import enum + +from llvmlite import ir +from llvmlite.binding import ffi + + +class TypeKind(enum.IntEnum): + # The LLVMTypeKind enum from llvm-c/Core.h + + void = 0 + half = 1 + float = 2 + double = 3 + x86_fp80 = 4 + fp128 = 5 + ppc_fp128 = 6 + label = 7 + integer = 8 + function = 9 + struct = 10 + array = 11 + pointer = 12 + vector = 13 + metadata = 14 + x86_mmx = 15 + token = 16 + scalable_vector = 17 + bfloat = 18 + x86_amx = 19 + + +_TypeKindToIRType = { + # All TypeKind here must have a TypeRef.as_ir() implementation + TypeKind.void: ir.VoidType, + TypeKind.half: ir.HalfType, + TypeKind.float: ir.FloatType, + TypeKind.double: ir.DoubleType, + TypeKind.integer: ir.IntType, + TypeKind.function: ir.FunctionType, + TypeKind.pointer: ir.PointerType, + TypeKind.array: ir.ArrayType, + TypeKind.vector: ir.VectorType, + TypeKind.struct: ir.LiteralStructType, +} + + +class TypeRef(ffi.ObjectRef): + """A weak reference to a LLVM type + """ + @property + def name(self): + """ + Get type name + """ + return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) + + @property + def is_struct(self): + """ + Returns true if the type is a struct type. + """ + return ffi.lib.LLVMPY_TypeIsStruct(self) + + @property + def is_pointer(self): + """ + Returns true if the type is a pointer type. + """ + return ffi.lib.LLVMPY_TypeIsPointer(self) + + @property + def is_array(self): + """ + Returns true if the type is an array type. + """ + return ffi.lib.LLVMPY_TypeIsArray(self) + + @property + def is_vector(self): + """ + Returns true if the type is a vector type. + """ + return ffi.lib.LLVMPY_TypeIsVector(self) + + @property + def is_function(self): + """ + Returns true if the type is a function type. + """ + return ffi.lib.LLVMPY_TypeIsFunction(self) + + @property + def is_function_vararg(self): + """ + Returns true if a function type accepts a variable number of arguments. + When the type is not a function, raises exception. + """ + if self.type_kind != TypeKind.function: + raise ValueError("Type {} is not a function".format(self)) + return ffi.lib.LLVMPY_IsFunctionVararg(self) + + @property + def elements(self): + """ + Returns iterator over enclosing types + """ + if self.is_pointer: + raise ValueError("Type {} doesn't contain elements.".format(self)) + return _TypeListIterator(ffi.lib.LLVMPY_ElementIter(self)) + + @property + def element_count(self): + """ + Returns the number of elements in an array or a vector. For scalable + vectors, returns minimum number of elements. When the type is neither + an array nor a vector, raises exception. + """ + if not self.is_array and not self.is_vector: + raise ValueError("Type {} is not an array nor vector".format(self)) + return ffi.lib.LLVMPY_GetTypeElementCount(self) + + @property + def type_width(self): + """ + Return the basic size of this type if it is a primitive type. These are + fixed by LLVM and are not target-dependent. + This will return zero if the type does not have a size or is not a + primitive type. + + If this is a scalable vector type, the scalable property will be set and + the runtime size will be a positive integer multiple of the base size. + + Note that this may not reflect the size of memory allocated for an + instance of the type or the number of bytes that are written when an + instance of the type is stored to memory. + """ + return ffi.lib.LLVMPY_GetTypeBitWidth(self) + + @property + def type_kind(self): + """ + Returns the LLVMTypeKind enumeration of this type. + """ + return TypeKind(ffi.lib.LLVMPY_GetTypeKind(self)) + + @property + def is_packed_struct(self): + return ffi.lib.LLVMPY_IsPackedStruct(self) + + @property + def is_literal_struct(self): + return ffi.lib.LLVMPY_IsLiteralStruct(self) + + @property + def is_opaque_struct(self): + return ffi.lib.LLVMPY_IsOpaqueStruct(self) + + def get_function_parameters(self) -> tuple["TypeRef"]: + nparams = ffi.lib.LLVMPY_CountParamTypes(self) + if nparams > 0: + out_buffer = (ffi.LLVMTypeRef * nparams)(None) + ffi.lib.LLVMPY_GetParamTypes(self, out_buffer) + return tuple(map(TypeRef, out_buffer)) + else: + return () + + def get_function_return(self) -> "TypeRef": + return TypeRef(ffi.lib.LLVMPY_GetReturnType(self)) + + def as_ir(self, ir_ctx: ir.Context) -> ir.Type: + """Convert into a ``llvmlite.ir.Type``. + """ + try: + cls = _TypeKindToIRType[self.type_kind] + except KeyError: + msg = f"as_ir() unsupported for TypeRef of {self.type_kind}" + raise TypeError(msg) + else: + return cls.from_llvm(self, ir_ctx) + + def __str__(self): + return ffi.ret_string(ffi.lib.LLVMPY_PrintType(self)) + + +class _TypeIterator(ffi.ObjectRef): + + def __next__(self): + vp = self._next() + if vp: + return TypeRef(vp) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _TypeListIterator(_TypeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeElementIter(self) + + def _next(self): + return ffi.lib.LLVMPY_ElementIterNext(self) + + +# FFI + +ffi.lib.LLVMPY_PrintType.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_PrintType.restype = c_void_p + +ffi.lib.LLVMPY_TypeIsPointer.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsPointer.restype = c_bool + +ffi.lib.LLVMPY_TypeIsArray.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsArray.restype = c_bool + +ffi.lib.LLVMPY_TypeIsVector.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsVector.restype = c_bool + +ffi.lib.LLVMPY_TypeIsStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsStruct.restype = c_bool + +ffi.lib.LLVMPY_TypeIsFunction.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsFunction.restype = c_bool + +ffi.lib.LLVMPY_IsPackedStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsPackedStruct.restype = c_bool + +ffi.lib.LLVMPY_IsOpaqueStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsOpaqueStruct.restype = c_bool + +ffi.lib.LLVMPY_IsLiteralStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsLiteralStruct.restype = c_bool + +ffi.lib.LLVMPY_GetReturnType.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetReturnType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_CountParamTypes.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_CountParamTypes.restype = c_uint + +ffi.lib.LLVMPY_GetParamTypes.argtypes = [ffi.LLVMTypeRef, + POINTER(ffi.LLVMTypeRef)] +ffi.lib.LLVMPY_GetParamTypes.restype = None + +ffi.lib.LLVMPY_IsFunctionVararg.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsFunctionVararg.restype = c_bool + +ffi.lib.LLVMPY_GetTypeKind.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeKind.restype = c_int + +ffi.lib.LLVMPY_GetTypeElementCount.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeElementCount.restype = c_int + +ffi.lib.LLVMPY_GetTypeBitWidth.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeBitWidth.restype = c_uint64 + +ffi.lib.LLVMPY_ElementIter.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ElementIter.restype = ffi.LLVMElementIterator + +ffi.lib.LLVMPY_ElementIterNext.argtypes = [ffi.LLVMElementIterator] +ffi.lib.LLVMPY_ElementIterNext.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_DisposeElementIter.argtypes = [ffi.LLVMElementIterator] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/value.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/value.py new file mode 100644 index 0000000000000000000000000000000000000000..611daa2393df8234186baa38814681e6e068d7b1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/binding/value.py @@ -0,0 +1,632 @@ +from ctypes import (POINTER, byref, cast, c_char_p, c_double, c_int, c_size_t, + c_uint, c_uint64, c_bool, c_void_p) +import enum + +from llvmlite.binding import ffi +from llvmlite.binding.common import _decode_string, _encode_string +from llvmlite.binding.typeref import TypeRef + + +class Linkage(enum.IntEnum): + # The LLVMLinkage enum from llvm-c/Core.h + + external = 0 + available_externally = 1 + linkonce_any = 2 + linkonce_odr = 3 + linkonce_odr_autohide = 4 + weak_any = 5 + weak_odr = 6 + appending = 7 + internal = 8 + private = 9 + dllimport = 10 + dllexport = 11 + external_weak = 12 + ghost = 13 + common = 14 + linker_private = 15 + linker_private_weak = 16 + + +class Visibility(enum.IntEnum): + # The LLVMVisibility enum from llvm-c/Core.h + + default = 0 + hidden = 1 + protected = 2 + + +class StorageClass(enum.IntEnum): + # The LLVMDLLStorageClass enum from llvm-c/Core.h + + default = 0 + dllimport = 1 + dllexport = 2 + + +class ValueKind(enum.IntEnum): + # The LLVMValueKind enum from llvm-c/Core.h + + argument = 0 + basic_block = 1 + memory_use = 2 + memory_def = 3 + memory_phi = 4 + + function = 5 + global_alias = 6 + global_ifunc = 7 + global_variable = 8 + block_address = 9 + constant_expr = 10 + constant_array = 11 + constant_struct = 12 + constant_vector = 13 + + undef_value = 14 + constant_aggregate_zero = 15 + constant_data_array = 16 + constant_data_vector = 17 + constant_int = 18 + constant_fp = 19 + constant_pointer_null = 20 + constant_token_none = 21 + + metadata_as_value = 22 + inline_asm = 23 + + instruction = 24 + poison_value = 25 + + +class ValueRef(ffi.ObjectRef): + """A weak reference to a LLVM value. + """ + + def __init__(self, ptr, kind, parents): + self._kind = kind + self._parents = parents + ffi.ObjectRef.__init__(self, ptr) + + def __str__(self): + with ffi.OutputString() as outstr: + ffi.lib.LLVMPY_PrintValueToString(self, outstr) + return str(outstr) + + @property + def module(self): + """ + The module this function or global variable value was obtained from. + """ + return self._parents.get('module') + + @property + def function(self): + """ + The function this argument or basic block value was obtained from. + """ + return self._parents.get('function') + + @property + def block(self): + """ + The block this instruction value was obtained from. + """ + return self._parents.get('block') + + @property + def instruction(self): + """ + The instruction this operand value was obtained from. + """ + return self._parents.get('instruction') + + @property + def is_global(self): + return self._kind == 'global' + + @property + def is_function(self): + return self._kind == 'function' + + @property + def is_block(self): + return self._kind == 'block' + + @property + def is_argument(self): + return self._kind == 'argument' + + @property + def is_instruction(self): + return self._kind == 'instruction' + + @property + def is_operand(self): + return self._kind == 'operand' + + @property + def is_constant(self): + return bool(ffi.lib.LLVMPY_IsConstant(self)) + + @property + def value_kind(self): + return ValueKind(ffi.lib.LLVMPY_GetValueKind(self)) + + @property + def name(self): + return _decode_string(ffi.lib.LLVMPY_GetValueName(self)) + + @name.setter + def name(self, val): + ffi.lib.LLVMPY_SetValueName(self, _encode_string(val)) + + @property + def linkage(self): + return Linkage(ffi.lib.LLVMPY_GetLinkage(self)) + + @linkage.setter + def linkage(self, value): + if not isinstance(value, Linkage): + value = Linkage[value] + ffi.lib.LLVMPY_SetLinkage(self, value) + + @property + def visibility(self): + return Visibility(ffi.lib.LLVMPY_GetVisibility(self)) + + @visibility.setter + def visibility(self, value): + if not isinstance(value, Visibility): + value = Visibility[value] + ffi.lib.LLVMPY_SetVisibility(self, value) + + @property + def storage_class(self): + return StorageClass(ffi.lib.LLVMPY_GetDLLStorageClass(self)) + + @storage_class.setter + def storage_class(self, value): + if not isinstance(value, StorageClass): + value = StorageClass[value] + ffi.lib.LLVMPY_SetDLLStorageClass(self, value) + + def add_function_attribute(self, attr): + """Only works on function value + + Parameters + ----------- + attr : str + attribute name + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + attrname = str(attr) + attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName( + _encode_string(attrname), len(attrname)) + if attrval == 0: + raise ValueError('no such attribute {!r}'.format(attrname)) + ffi.lib.LLVMPY_AddFunctionAttr(self, attrval) + + @property + def type(self): + """ + This value's LLVM type. + """ + # XXX what does this return? + return TypeRef(ffi.lib.LLVMPY_TypeOf(self)) + + @property + def global_value_type(self): + """ + Uses ``LLVMGlobalGetValueType()``. + Needed for opaque pointers in globals. + > For globals, use getValueType(). + See https://llvm.org/docs/OpaquePointers.html#migration-instructions + """ + assert self.is_global or self.is_function + return TypeRef(ffi.lib.LLVMPY_GlobalGetValueType(self)) + + @property + def is_declaration(self): + """ + Whether this value (presumably global) is defined in the current + module. + """ + if not (self.is_global or self.is_function): + raise ValueError('expected global or function value, got %s' + % (self._kind,)) + return ffi.lib.LLVMPY_IsDeclaration(self) + + @property + def attributes(self): + """ + Return an iterator over this value's attributes. + The iterator will yield a string for each attribute. + """ + itr = iter(()) + if self.is_function: + it = ffi.lib.LLVMPY_FunctionAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.is_instruction: + if self.opcode == 'call': + it = ffi.lib.LLVMPY_CallInstAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.opcode == 'invoke': + it = ffi.lib.LLVMPY_InvokeInstAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.is_global: + it = ffi.lib.LLVMPY_GlobalAttributesIter(self) + itr = _AttributeSetIterator(it) + elif self.is_argument: + it = ffi.lib.LLVMPY_ArgumentAttributesIter(self) + itr = _AttributeSetIterator(it) + return itr + + @property + def blocks(self): + """ + Return an iterator over this function's blocks. + The iterator will yield a ValueRef for each block. + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_FunctionBlocksIter(self) + parents = self._parents.copy() + parents.update(function=self) + return _BlocksIterator(it, parents) + + @property + def arguments(self): + """ + Return an iterator over this function's arguments. + The iterator will yield a ValueRef for each argument. + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_FunctionArgumentsIter(self) + parents = self._parents.copy() + parents.update(function=self) + return _ArgumentsIterator(it, parents) + + @property + def instructions(self): + """ + Return an iterator over this block's instructions. + The iterator will yield a ValueRef for each instruction. + """ + if not self.is_block: + raise ValueError('expected block value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_BlockInstructionsIter(self) + parents = self._parents.copy() + parents.update(block=self) + return _InstructionsIterator(it, parents) + + @property + def operands(self): + """ + Return an iterator over this instruction's operands. + The iterator will yield a ValueRef for each operand. + """ + if not self.is_instruction: + raise ValueError('expected instruction value, got %s' + % (self._kind,)) + it = ffi.lib.LLVMPY_InstructionOperandsIter(self) + parents = self._parents.copy() + parents.update(instruction=self) + return _OperandsIterator(it, parents) + + @property + def opcode(self): + if not self.is_instruction: + raise ValueError('expected instruction value, got %s' + % (self._kind,)) + return ffi.ret_string(ffi.lib.LLVMPY_GetOpcodeName(self)) + + @property + def incoming_blocks(self): + """ + Return an iterator over this phi instruction's incoming blocks. + The iterator will yield a ValueRef for each block. + """ + if not self.is_instruction or self.opcode != 'phi': + raise ValueError('expected phi instruction value, got %s' + % (self._kind,)) + it = ffi.lib.LLVMPY_PhiIncomingBlocksIter(self) + parents = self._parents.copy() + parents.update(instruction=self) + return _IncomingBlocksIterator(it, parents) + + def get_constant_value(self, signed_int=False, round_fp=False): + """ + Return the constant value, either as a literal (when supported) + or as a string. + + Parameters + ----------- + signed_int : bool + if True and the constant is an integer, returns a signed version + round_fp : bool + if True and the constant is a floating point value, rounds the + result upon accuracy loss (e.g., when querying an fp128 value). + By default, raises an exception on accuracy loss + """ + if not self.is_constant: + raise ValueError('expected constant value, got %s' + % (self._kind,)) + + if self.value_kind == ValueKind.constant_int: + # Python integers are also arbitrary-precision + little_endian = c_bool(False) + words = ffi.lib.LLVMPY_GetConstantIntNumWords(self) + ptr = ffi.lib.LLVMPY_GetConstantIntRawValue( + self, byref(little_endian)) + asbytes = bytes(cast(ptr, POINTER(c_uint64 * words)).contents) + return int.from_bytes( + asbytes, + ('little' if little_endian.value else 'big'), + signed=signed_int, + ) + elif self.value_kind == ValueKind.constant_fp: + # Convert floating-point values to double-precision (Python float) + accuracy_loss = c_bool(False) + value = ffi.lib.LLVMPY_GetConstantFPValue(self, + byref(accuracy_loss)) + if accuracy_loss.value and not round_fp: + raise ValueError( + 'Accuracy loss encountered in conversion of constant ' + f'value {str(self)}') + + return value + + # Otherwise, return the IR string + return str(self) + + +class _ValueIterator(ffi.ObjectRef): + + kind = None # derived classes must specify the Value kind value + # as class attribute + + def __init__(self, ptr, parents): + ffi.ObjectRef.__init__(self, ptr) + # Keep parent objects (module, function, etc) alive + self._parents = parents + if self.kind is None: + raise NotImplementedError('%s must specify kind attribute' + % (type(self).__name__,)) + + def __next__(self): + vp = self._next() + if vp: + return ValueRef(vp, self.kind, self._parents) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _AttributeIterator(ffi.ObjectRef): + + def __next__(self): + vp = self._next() + if vp: + return vp + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _AttributeListIterator(_AttributeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeAttributeListIter(self) + + def _next(self): + return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeListIterNext(self)) + + +class _AttributeSetIterator(_AttributeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeAttributeSetIter(self) + + def _next(self): + return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeSetIterNext(self)) + + +class _BlocksIterator(_ValueIterator): + + kind = 'block' + + def _dispose(self): + self._capi.LLVMPY_DisposeBlocksIter(self) + + def _next(self): + return ffi.lib.LLVMPY_BlocksIterNext(self) + + +class _ArgumentsIterator(_ValueIterator): + + kind = 'argument' + + def _dispose(self): + self._capi.LLVMPY_DisposeArgumentsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_ArgumentsIterNext(self) + + +class _InstructionsIterator(_ValueIterator): + + kind = 'instruction' + + def _dispose(self): + self._capi.LLVMPY_DisposeInstructionsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_InstructionsIterNext(self) + + +class _OperandsIterator(_ValueIterator): + + kind = 'operand' + + def _dispose(self): + self._capi.LLVMPY_DisposeOperandsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_OperandsIterNext(self) + + +class _IncomingBlocksIterator(_ValueIterator): + + kind = 'block' + + def _dispose(self): + self._capi.LLVMPY_DisposeIncomingBlocksIter(self) + + def _next(self): + return ffi.lib.LLVMPY_IncomingBlocksIterNext(self) + + +# FFI + +ffi.lib.LLVMPY_PrintValueToString.argtypes = [ + ffi.LLVMValueRef, + POINTER(c_char_p) +] + +ffi.lib.LLVMPY_GetGlobalParent.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetGlobalParent.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_GetValueName.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetValueName.restype = c_char_p + +ffi.lib.LLVMPY_SetValueName.argtypes = [ffi.LLVMValueRef, c_char_p] + +ffi.lib.LLVMPY_TypeOf.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_TypeOf.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_GlobalGetValueType.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GlobalGetValueType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_GetTypeName.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeName.restype = c_void_p + +ffi.lib.LLVMPY_GetLinkage.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetLinkage.restype = c_int + +ffi.lib.LLVMPY_SetLinkage.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetVisibility.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetVisibility.restype = c_int + +ffi.lib.LLVMPY_SetVisibility.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetDLLStorageClass.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetDLLStorageClass.restype = c_int + +ffi.lib.LLVMPY_SetDLLStorageClass.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetEnumAttributeKindForName.argtypes = [c_char_p, c_size_t] +ffi.lib.LLVMPY_GetEnumAttributeKindForName.restype = c_uint + +ffi.lib.LLVMPY_AddFunctionAttr.argtypes = [ffi.LLVMValueRef, c_uint] + +ffi.lib.LLVMPY_IsDeclaration.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_IsDeclaration.restype = c_int + +ffi.lib.LLVMPY_FunctionAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_CallInstAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_CallInstAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_InvokeInstAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_InvokeInstAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_GlobalAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GlobalAttributesIter.restype = ffi.LLVMAttributeSetIterator + +ffi.lib.LLVMPY_ArgumentAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_ArgumentAttributesIter.restype = ffi.LLVMAttributeSetIterator + +ffi.lib.LLVMPY_FunctionBlocksIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionBlocksIter.restype = ffi.LLVMBlocksIterator + +ffi.lib.LLVMPY_FunctionArgumentsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionArgumentsIter.restype = ffi.LLVMArgumentsIterator + +ffi.lib.LLVMPY_BlockInstructionsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_BlockInstructionsIter.restype = ffi.LLVMInstructionsIterator + +ffi.lib.LLVMPY_InstructionOperandsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_InstructionOperandsIter.restype = ffi.LLVMOperandsIterator + +ffi.lib.LLVMPY_PhiIncomingBlocksIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_PhiIncomingBlocksIter.restype = ffi.LLVMIncomingBlocksIterator + +ffi.lib.LLVMPY_DisposeAttributeListIter.argtypes = [ + ffi.LLVMAttributeListIterator] + +ffi.lib.LLVMPY_DisposeAttributeSetIter.argtypes = [ffi.LLVMAttributeSetIterator] + +ffi.lib.LLVMPY_DisposeBlocksIter.argtypes = [ffi.LLVMBlocksIterator] + +ffi.lib.LLVMPY_DisposeInstructionsIter.argtypes = [ffi.LLVMInstructionsIterator] + +ffi.lib.LLVMPY_DisposeOperandsIter.argtypes = [ffi.LLVMOperandsIterator] + +ffi.lib.LLVMPY_DisposeIncomingBlocksIter.argtypes = [ + ffi.LLVMIncomingBlocksIterator] + +ffi.lib.LLVMPY_AttributeListIterNext.argtypes = [ffi.LLVMAttributeListIterator] +ffi.lib.LLVMPY_AttributeListIterNext.restype = c_void_p + +ffi.lib.LLVMPY_AttributeSetIterNext.argtypes = [ffi.LLVMAttributeSetIterator] +ffi.lib.LLVMPY_AttributeSetIterNext.restype = c_void_p + +ffi.lib.LLVMPY_BlocksIterNext.argtypes = [ffi.LLVMBlocksIterator] +ffi.lib.LLVMPY_BlocksIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_ArgumentsIterNext.argtypes = [ffi.LLVMArgumentsIterator] +ffi.lib.LLVMPY_ArgumentsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_InstructionsIterNext.argtypes = [ffi.LLVMInstructionsIterator] +ffi.lib.LLVMPY_InstructionsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_OperandsIterNext.argtypes = [ffi.LLVMOperandsIterator] +ffi.lib.LLVMPY_OperandsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_IncomingBlocksIterNext.argtypes = [ + ffi.LLVMIncomingBlocksIterator] +ffi.lib.LLVMPY_IncomingBlocksIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_GetOpcodeName.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetOpcodeName.restype = c_void_p + +ffi.lib.LLVMPY_IsConstant.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_IsConstant.restype = c_bool + +ffi.lib.LLVMPY_GetValueKind.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetValueKind.restype = c_int + +ffi.lib.LLVMPY_GetConstantIntRawValue.argtypes = [ffi.LLVMValueRef, + POINTER(c_bool)] +ffi.lib.LLVMPY_GetConstantIntRawValue.restype = POINTER(c_uint64) + +ffi.lib.LLVMPY_GetConstantIntNumWords.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetConstantIntNumWords.restype = c_uint + +ffi.lib.LLVMPY_GetConstantFPValue.argtypes = [ffi.LLVMValueRef, + POINTER(c_bool)] +ffi.lib.LLVMPY_GetConstantFPValue.restype = c_double diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a0737b2d5325d5c40a8953520a260c013ed48f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__init__.py @@ -0,0 +1,11 @@ +""" +This subpackage implements the LLVM IR classes in pure python +""" + +from .types import * +from .values import * +from .module import * +from .builder import * +from .instructions import * +from .transforms import * +from .context import Context, global_context diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19dc2baf537e65d1e4f65651fedff5910c878d6e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a9dbe25e56fbb2b408fa0a2ba23408ccdb2d1f9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/_utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/builder.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/builder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46eaceed1e2cebe1acdb490574fdef58e3a05201 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/builder.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/context.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/context.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73f1e3d47f77c511e09b53e7125c07d1ff1f4edc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/context.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/instructions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/instructions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd25456b89b235ce2c1a8b19aeee58c7309dfc60 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/instructions.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/module.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/module.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a50d747751a341b8252ac7327bd528eb2d681dd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/module.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/transforms.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17e5dc634914fa8bd07eae53e17ec5f14296a985 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/transforms.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71603ece83fe180047000c70614c633a9f3e044f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/types.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/values.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/values.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7612abfe65e4738b23a41798a59786b94d331f8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/__pycache__/values.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8287d77afb84f750be00ef0b001a175507c59da4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/_utils.py @@ -0,0 +1,80 @@ +from collections import defaultdict + + +class DuplicatedNameError(NameError): + pass + + +class NameScope(object): + def __init__(self): + self._useset = set(['']) + self._basenamemap = defaultdict(int) + + def is_used(self, name): + return name in self._useset + + def register(self, name, deduplicate=False): + if deduplicate: + name = self.deduplicate(name) + elif self.is_used(name): + raise DuplicatedNameError(name) + self._useset.add(name) + return name + + def deduplicate(self, name): + basename = name + while self.is_used(name): + ident = self._basenamemap[basename] + 1 + self._basenamemap[basename] = ident + name = "{0}.{1}".format(basename, ident) + return name + + def get_child(self): + return type(self)(parent=self) + + +class _StrCaching(object): + + def _clear_string_cache(self): + try: + del self.__cached_str + except AttributeError: + pass + + def __str__(self): + try: + return self.__cached_str + except AttributeError: + s = self.__cached_str = self._to_string() + return s + + +class _StringReferenceCaching(object): + + def get_reference(self): + try: + return self.__cached_refstr + except AttributeError: + s = self.__cached_refstr = self._get_reference() + return s + + +class _HasMetadata(object): + + def set_metadata(self, name, node): + """ + Attach unnamed metadata *node* to the metadata slot *name* of this + value. + """ + self.metadata[name] = node + + def _stringify_metadata(self, leading_comma=False): + if self.metadata: + buf = [] + if leading_comma: + buf.append("") + buf += ["!{0} {1}".format(k, v.get_reference()) + for k, v in self.metadata.items()] + return ', '.join(buf) + else: + return '' diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/builder.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1ecf74deb39d6ee92a4cba899702241c6b44cc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/builder.py @@ -0,0 +1,1120 @@ +import contextlib +import functools + +from llvmlite.ir import instructions, types, values + +_CMP_MAP = { + '>': 'gt', + '<': 'lt', + '==': 'eq', + '!=': 'ne', + '>=': 'ge', + '<=': 'le', +} + + +def _unop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, arg, name='', flags=()): + instr = cls(self.block, arg.type, opname, [arg], name, flags) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _binop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, lhs, rhs, name='', flags=()): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + instr = cls(self.block, lhs.type, opname, (lhs, rhs), name, flags) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _binop_with_overflow(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, lhs, rhs, name=''): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + ty = lhs.type + if not isinstance(ty, types.IntType): + raise TypeError("expected an integer type, got %s" % (ty,)) + bool_ty = types.IntType(1) + + mod = self.module + fnty = types.FunctionType(types.LiteralStructType([ty, bool_ty]), + [ty, ty]) + fn = mod.declare_intrinsic("llvm.%s.with.overflow" % (opname,), + [ty], fnty) + ret = self.call(fn, [lhs, rhs], name=name) + return ret + + return wrapped + + return wrap + + +def _uniop(opname, cls=instructions.Instruction): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + instr = cls(self.block, operand.type, opname, [operand], name) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _uniop_intrinsic_int(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + if not isinstance(operand.type, types.IntType): + raise TypeError( + "expected an integer type, got %s" % + operand.type) + fn = self.module.declare_intrinsic(opname, [operand.type]) + return self.call(fn, [operand], name) + + return wrapped + + return wrap + + +def _uniop_intrinsic_float(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, name=''): + if not isinstance( + operand.type, (types.FloatType, types.DoubleType)): + raise TypeError("expected a float type, got %s" % operand.type) + fn = self.module.declare_intrinsic(opname, [operand.type]) + return self.call(fn, [operand], name) + + return wrapped + + return wrap + + +def _uniop_intrinsic_with_flag(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, operand, flag, name=''): + if not isinstance(operand.type, types.IntType): + raise TypeError( + "expected an integer type, got %s" % + operand.type) + if not (isinstance(flag.type, types.IntType) and + flag.type.width == 1): + raise TypeError("expected an i1 type, got %s" % flag.type) + fn = self.module.declare_intrinsic( + opname, [operand.type, flag.type]) + return self.call(fn, [operand, flag], name) + + return wrapped + + return wrap + + +def _triop_intrinsic(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, a, b, c, name=''): + if a.type != b.type or b.type != c.type: + raise TypeError( + "expected types to be the same, got %s, %s, %s" % ( + a.type, + b.type, + c.type)) + elif not isinstance( + a.type, + (types.HalfType, types.FloatType, types.DoubleType)): + raise TypeError( + "expected an floating point type, got %s" % + a.type) + fn = self.module.declare_intrinsic(opname, [a.type, b.type, c.type]) + return self.call(fn, [a, b, c], name) + + return wrapped + + return wrap + + +def _castop(opname, cls=instructions.CastInstr): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, val, typ, name=''): + if val.type == typ: + return val + instr = cls(self.block, opname, val, typ, name) + self._insert(instr) + return instr + + return wrapped + + return wrap + + +def _label_suffix(label, suffix): + """Returns (label + suffix) or a truncated version if it's too long. + Parameters + ---------- + label : str + Label name + suffix : str + Label suffix + """ + if len(label) > 50: + nhead = 25 + return ''.join([label[:nhead], '..', suffix]) + else: + return label + suffix + + +class IRBuilder(object): + def __init__(self, block=None): + self._block = block + self._anchor = len(block.instructions) if block else 0 + self.debug_metadata = None + + @property + def block(self): + """ + The current basic block. + """ + return self._block + + basic_block = block + + @property + def function(self): + """ + The current function. + """ + return self.block.parent + + @property + def module(self): + """ + The current module. + """ + return self.block.parent.module + + def position_before(self, instr): + """ + Position immediately before the given instruction. The current block + is also changed to the instruction's basic block. + """ + self._block = instr.parent + self._anchor = self._block.instructions.index(instr) + + def position_after(self, instr): + """ + Position immediately after the given instruction. The current block + is also changed to the instruction's basic block. + """ + self._block = instr.parent + self._anchor = self._block.instructions.index(instr) + 1 + + def position_at_start(self, block): + """ + Position at the start of the basic *block*. + """ + self._block = block + self._anchor = 0 + + def position_at_end(self, block): + """ + Position at the end of the basic *block*. + """ + self._block = block + self._anchor = len(block.instructions) + + def append_basic_block(self, name=''): + """ + Append a basic block, with the given optional *name*, to the current + function. The current block is not changed. The new block is returned. + """ + return self.function.append_basic_block(name) + + def remove(self, instr): + """Remove the given instruction.""" + idx = self._block.instructions.index(instr) + del self._block.instructions[idx] + if self._block.terminator == instr: + self._block.terminator = None + if self._anchor > idx: + self._anchor -= 1 + + @contextlib.contextmanager + def goto_block(self, block): + """ + A context manager which temporarily positions the builder at the end + of basic block *bb* (but before any terminator). + """ + old_block = self.basic_block + term = block.terminator + if term is not None: + self.position_before(term) + else: + self.position_at_end(block) + try: + yield + finally: + self.position_at_end(old_block) + + @contextlib.contextmanager + def goto_entry_block(self): + """ + A context manager which temporarily positions the builder at the + end of the function's entry block. + """ + with self.goto_block(self.function.entry_basic_block): + yield + + @contextlib.contextmanager + def _branch_helper(self, bbenter, bbexit): + self.position_at_end(bbenter) + yield bbexit + if self.basic_block.terminator is None: + self.branch(bbexit) + + @contextlib.contextmanager + def if_then(self, pred, likely=None): + """ + A context manager which sets up a conditional basic block based + on the given predicate (a i1 value). If the conditional block + is not explicitly terminated, a branch will be added to the next + block. + If *likely* is given, its boolean value indicates whether the + predicate is likely to be true or not, and metadata is issued + for LLVM's optimizers to account for that. + """ + bb = self.basic_block + bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if')) + bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif')) + br = self.cbranch(pred, bbif, bbend) + if likely is not None: + br.set_weights([99, 1] if likely else [1, 99]) + + with self._branch_helper(bbif, bbend): + yield bbend + + self.position_at_end(bbend) + + @contextlib.contextmanager + def if_else(self, pred, likely=None): + """ + A context manager which sets up two conditional basic blocks based + on the given predicate (a i1 value). + A tuple of context managers is yield'ed. Each context manager + acts as a if_then() block. + *likely* has the same meaning as in if_then(). + + Typical use:: + with builder.if_else(pred) as (then, otherwise): + with then: + # emit instructions for when the predicate is true + with otherwise: + # emit instructions for when the predicate is false + """ + bb = self.basic_block + bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if')) + bbelse = self.append_basic_block(name=_label_suffix(bb.name, '.else')) + bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif')) + br = self.cbranch(pred, bbif, bbelse) + if likely is not None: + br.set_weights([99, 1] if likely else [1, 99]) + + then = self._branch_helper(bbif, bbend) + otherwise = self._branch_helper(bbelse, bbend) + + yield then, otherwise + + self.position_at_end(bbend) + + def _insert(self, instr): + if self.debug_metadata is not None and 'dbg' not in instr.metadata: + instr.metadata['dbg'] = self.debug_metadata + self._block.instructions.insert(self._anchor, instr) + self._anchor += 1 + + def _set_terminator(self, term): + assert not self.block.is_terminated + self._insert(term) + self.block.terminator = term + return term + + # + # Arithmetic APIs + # + + @_binop('shl') + def shl(self, lhs, rhs, name=''): + """ + Left integer shift: + name = lhs << rhs + """ + + @_binop('lshr') + def lshr(self, lhs, rhs, name=''): + """ + Logical (unsigned) right integer shift: + name = lhs >> rhs + """ + + @_binop('ashr') + def ashr(self, lhs, rhs, name=''): + """ + Arithmetic (signed) right integer shift: + name = lhs >> rhs + """ + + @_binop('add') + def add(self, lhs, rhs, name=''): + """ + Integer addition: + name = lhs + rhs + """ + + @_binop('fadd') + def fadd(self, lhs, rhs, name=''): + """ + Floating-point addition: + name = lhs + rhs + """ + + @_binop('sub') + def sub(self, lhs, rhs, name=''): + """ + Integer subtraction: + name = lhs - rhs + """ + + @_binop('fsub') + def fsub(self, lhs, rhs, name=''): + """ + Floating-point subtraction: + name = lhs - rhs + """ + + @_binop('mul') + def mul(self, lhs, rhs, name=''): + """ + Integer multiplication: + name = lhs * rhs + """ + + @_binop('fmul') + def fmul(self, lhs, rhs, name=''): + """ + Floating-point multiplication: + name = lhs * rhs + """ + + @_binop('udiv') + def udiv(self, lhs, rhs, name=''): + """ + Unsigned integer division: + name = lhs / rhs + """ + + @_binop('sdiv') + def sdiv(self, lhs, rhs, name=''): + """ + Signed integer division: + name = lhs / rhs + """ + + @_binop('fdiv') + def fdiv(self, lhs, rhs, name=''): + """ + Floating-point division: + name = lhs / rhs + """ + + @_binop('urem') + def urem(self, lhs, rhs, name=''): + """ + Unsigned integer remainder: + name = lhs % rhs + """ + + @_binop('srem') + def srem(self, lhs, rhs, name=''): + """ + Signed integer remainder: + name = lhs % rhs + """ + + @_binop('frem') + def frem(self, lhs, rhs, name=''): + """ + Floating-point remainder: + name = lhs % rhs + """ + + @_binop('or') + def or_(self, lhs, rhs, name=''): + """ + Bitwise integer OR: + name = lhs | rhs + """ + + @_binop('and') + def and_(self, lhs, rhs, name=''): + """ + Bitwise integer AND: + name = lhs & rhs + """ + + @_binop('xor') + def xor(self, lhs, rhs, name=''): + """ + Bitwise integer XOR: + name = lhs ^ rhs + """ + + @_binop_with_overflow('sadd') + def sadd_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer addition with overflow: + name = {result, overflow bit} = lhs + rhs + """ + + @_binop_with_overflow('smul') + def smul_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer multiplication with overflow: + name = {result, overflow bit} = lhs * rhs + """ + + @_binop_with_overflow('ssub') + def ssub_with_overflow(self, lhs, rhs, name=''): + """ + Signed integer subtraction with overflow: + name = {result, overflow bit} = lhs - rhs + """ + + @_binop_with_overflow('uadd') + def uadd_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer addition with overflow: + name = {result, overflow bit} = lhs + rhs + """ + + @_binop_with_overflow('umul') + def umul_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer multiplication with overflow: + name = {result, overflow bit} = lhs * rhs + """ + + @_binop_with_overflow('usub') + def usub_with_overflow(self, lhs, rhs, name=''): + """ + Unsigned integer subtraction with overflow: + name = {result, overflow bit} = lhs - rhs + """ + + # + # Unary APIs + # + + def not_(self, value, name=''): + """ + Bitwise integer complement: + name = ~value + """ + if isinstance(value.type, types.VectorType): + rhs = values.Constant(value.type, (-1,) * value.type.count) + else: + rhs = values.Constant(value.type, -1) + return self.xor(value, rhs, name=name) + + def neg(self, value, name=''): + """ + Integer negative: + name = -value + """ + return self.sub(values.Constant(value.type, 0), value, name=name) + + @_unop('fneg') + def fneg(self, arg, name='', flags=()): + """ + Floating-point negative: + name = -arg + """ + + # + # Comparison APIs + # + + def _icmp(self, prefix, cmpop, lhs, rhs, name): + try: + op = _CMP_MAP[cmpop] + except KeyError: + raise ValueError("invalid comparison %r for icmp" % (cmpop,)) + if cmpop not in ('==', '!='): + op = prefix + op + instr = instructions.ICMPInstr(self.block, op, lhs, rhs, name=name) + self._insert(instr) + return instr + + def icmp_signed(self, cmpop, lhs, rhs, name=''): + """ + Signed integer comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._icmp('s', cmpop, lhs, rhs, name) + + def icmp_unsigned(self, cmpop, lhs, rhs, name=''): + """ + Unsigned integer (or pointer) comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._icmp('u', cmpop, lhs, rhs, name) + + def fcmp_ordered(self, cmpop, lhs, rhs, name='', flags=()): + """ + Floating-point ordered comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + if cmpop in _CMP_MAP: + op = 'o' + _CMP_MAP[cmpop] + else: + op = cmpop + instr = instructions.FCMPInstr( + self.block, op, lhs, rhs, name=name, flags=flags) + self._insert(instr) + return instr + + def fcmp_unordered(self, cmpop, lhs, rhs, name='', flags=()): + """ + Floating-point unordered comparison: + name = lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + if cmpop in _CMP_MAP: + op = 'u' + _CMP_MAP[cmpop] + else: + op = cmpop + instr = instructions.FCMPInstr( + self.block, op, lhs, rhs, name=name, flags=flags) + self._insert(instr) + return instr + + def select(self, cond, lhs, rhs, name='', flags=()): + """ + Ternary select operator: + name = cond ? lhs : rhs + """ + instr = instructions.SelectInstr(self.block, cond, lhs, rhs, name=name, + flags=flags) + self._insert(instr) + return instr + + # + # Cast APIs + # + + @_castop('trunc') + def trunc(self, value, typ, name=''): + """ + Truncating integer downcast to a smaller type: + name = (typ) value + """ + + @_castop('zext') + def zext(self, value, typ, name=''): + """ + Zero-extending integer upcast to a larger type: + name = (typ) value + """ + + @_castop('sext') + def sext(self, value, typ, name=''): + """ + Sign-extending integer upcast to a larger type: + name = (typ) value + """ + + @_castop('fptrunc') + def fptrunc(self, value, typ, name=''): + """ + Floating-point downcast to a less precise type: + name = (typ) value + """ + + @_castop('fpext') + def fpext(self, value, typ, name=''): + """ + Floating-point upcast to a more precise type: + name = (typ) value + """ + + @_castop('bitcast') + def bitcast(self, value, typ, name=''): + """ + Pointer cast to a different pointer type: + name = (typ) value + """ + + @_castop('addrspacecast') + def addrspacecast(self, value, typ, name=''): + """ + Pointer cast to a different address space: + name = (typ) value + """ + + @_castop('fptoui') + def fptoui(self, value, typ, name=''): + """ + Convert floating-point to unsigned integer: + name = (typ) value + """ + + @_castop('uitofp') + def uitofp(self, value, typ, name=''): + """ + Convert unsigned integer to floating-point: + name = (typ) value + """ + + @_castop('fptosi') + def fptosi(self, value, typ, name=''): + """ + Convert floating-point to signed integer: + name = (typ) value + """ + + @_castop('sitofp') + def sitofp(self, value, typ, name=''): + """ + Convert signed integer to floating-point: + name = (typ) value + """ + + @_castop('ptrtoint') + def ptrtoint(self, value, typ, name=''): + """ + Cast pointer to integer: + name = (typ) value + """ + + @_castop('inttoptr') + def inttoptr(self, value, typ, name=''): + """ + Cast integer to pointer: + name = (typ) value + """ + + # + # Memory APIs + # + + def alloca(self, typ, size=None, name=''): + """ + Stack-allocate a slot for *size* elements of the given type. + (default one element) + """ + if size is None: + pass + elif isinstance(size, (values.Value, values.Constant)): + assert isinstance(size.type, types.IntType) + else: + # If it is not a Value instance, + # assume to be a Python integer. + size = values.Constant(types.IntType(32), size) + + al = instructions.AllocaInstr(self.block, typ, size, name) + self._insert(al) + return al + + def load(self, ptr, name='', align=None, typ=None): + """ + Load value from pointer, with optional guaranteed alignment: + name = *ptr + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot load from value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + ld = instructions.LoadInstr(self.block, ptr, name, typ=typ) + ld.align = align + self._insert(ld) + return ld + + def store(self, value, ptr, align=None): + """ + Store value to pointer, with optional guaranteed alignment: + *ptr = name + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot store to value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + if not ptr.type.is_opaque and ptr.type.pointee != value.type: + raise TypeError("cannot store %s to %s: mismatching types" + % (value.type, ptr.type)) + st = instructions.StoreInstr(self.block, value, ptr) + st.align = align + self._insert(st) + return st + + def load_atomic(self, ptr, ordering, align, name='', typ=None): + """ + Load value from pointer, with optional guaranteed alignment: + name = *ptr + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot load from value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + ld = instructions.LoadAtomicInstr( + self.block, ptr, ordering, align, name, typ=typ) + self._insert(ld) + return ld + + def store_atomic(self, value, ptr, ordering, align): + """ + Store value to pointer, with optional guaranteed alignment: + *ptr = name + """ + if not isinstance(ptr.type, types.PointerType): + msg = "cannot store to value of type %s (%r): not a pointer" + raise TypeError(msg % (ptr.type, str(ptr))) + if ptr.type.pointee != value.type: + raise TypeError("cannot store %s to %s: mismatching types" + % (value.type, ptr.type)) + st = instructions.StoreAtomicInstr( + self.block, value, ptr, ordering, align) + self._insert(st) + return st + + # + # Terminators APIs + # + + def switch(self, value, default): + """ + Create a switch-case with a single *default* target. + """ + swt = instructions.SwitchInstr(self.block, 'switch', value, default) + self._set_terminator(swt) + return swt + + def branch(self, target): + """ + Unconditional branch to *target*. + """ + br = instructions.Branch(self.block, "br", [target]) + self._set_terminator(br) + return br + + def cbranch(self, cond, truebr, falsebr): + """ + Conditional branch to *truebr* if *cond* is true, else to *falsebr*. + """ + br = instructions.ConditionalBranch(self.block, "br", + [cond, truebr, falsebr]) + self._set_terminator(br) + return br + + def branch_indirect(self, addr): + """ + Indirect branch to target *addr*. + """ + br = instructions.IndirectBranch(self.block, "indirectbr", addr) + self._set_terminator(br) + return br + + def ret_void(self): + """ + Return from function without a value. + """ + return self._set_terminator( + instructions.Ret(self.block, "ret void")) + + def ret(self, value): + """ + Return from function with the given *value*. + """ + return self._set_terminator( + instructions.Ret(self.block, "ret", value)) + + def resume(self, landingpad): + """ + Resume an in-flight exception. + """ + br = instructions.Branch(self.block, "resume", [landingpad]) + self._set_terminator(br) + return br + + # Call APIs + + def call(self, fn, args, name='', cconv=None, tail=False, fastmath=(), + attrs=(), arg_attrs=None): + """ + Call function *fn* with *args*: + name = fn(args...) + """ + inst = instructions.CallInstr(self.block, fn, args, name=name, + cconv=cconv, tail=tail, fastmath=fastmath, + attrs=attrs, arg_attrs=arg_attrs) + self._insert(inst) + return inst + + def asm(self, ftype, asm, constraint, args, side_effect, name=''): + """ + Inline assembler. + """ + asm = instructions.InlineAsm(ftype, asm, constraint, side_effect) + return self.call(asm, args, name) + + def load_reg(self, reg_type, reg_name, name=''): + """ + Load a register value into an LLVM value. + Example: v = load_reg(IntType(32), "eax") + """ + ftype = types.FunctionType(reg_type, []) + return self.asm(ftype, "", "={%s}" % reg_name, [], False, name) + + def store_reg(self, value, reg_type, reg_name, name=''): + """ + Store an LLVM value inside a register + Example: + store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax") + """ + ftype = types.FunctionType(types.VoidType(), [reg_type]) + return self.asm(ftype, "", "{%s}" % reg_name, [value], True, name) + + def invoke(self, fn, args, normal_to, unwind_to, + name='', cconv=None, fastmath=(), attrs=(), arg_attrs=None): + inst = instructions.InvokeInstr(self.block, fn, args, normal_to, + unwind_to, name=name, cconv=cconv, + fastmath=fastmath, attrs=attrs, + arg_attrs=arg_attrs) + self._set_terminator(inst) + return inst + + # GEP APIs + + def gep(self, ptr, indices, inbounds=False, name='', source_etype=None): + """ + Compute effective address (getelementptr): + name = getelementptr ptr, + """ + instr = instructions.GEPInstr(self.block, ptr, indices, + inbounds=inbounds, name=name, + source_etype=source_etype) + self._insert(instr) + return instr + + # Vector Operations APIs + + def extract_element(self, vector, idx, name=''): + """ + Returns the value at position idx. + """ + instr = instructions.ExtractElement(self.block, vector, idx, name=name) + self._insert(instr) + return instr + + def insert_element(self, vector, value, idx, name=''): + """ + Returns vector with vector[idx] replaced by value. + The result is undefined if the idx is larger or equal the vector length. + """ + instr = instructions.InsertElement(self.block, vector, value, idx, + name=name) + self._insert(instr) + return instr + + def shuffle_vector(self, vector1, vector2, mask, name=''): + """ + Constructs a permutation of elements from *vector1* and *vector2*. + Returns a new vector in the same length of *mask*. + + * *vector1* and *vector2* must have the same element type. + * *mask* must be a constant vector of integer types. + """ + instr = instructions.ShuffleVector(self.block, vector1, vector2, mask, + name=name) + self._insert(instr) + return instr + + # Aggregate APIs + + def extract_value(self, agg, idx, name=''): + """ + Extract member number *idx* from aggregate. + """ + if not isinstance(idx, (tuple, list)): + idx = [idx] + instr = instructions.ExtractValue(self.block, agg, idx, name=name) + self._insert(instr) + return instr + + def insert_value(self, agg, value, idx, name=''): + """ + Insert *value* into member number *idx* from aggregate. + """ + if not isinstance(idx, (tuple, list)): + idx = [idx] + instr = instructions.InsertValue(self.block, agg, value, idx, name=name) + self._insert(instr) + return instr + + # PHI APIs + + def phi(self, typ, name='', flags=()): + inst = instructions.PhiInstr(self.block, typ, name=name, flags=flags) + self._insert(inst) + return inst + + # Special API + + def unreachable(self): + inst = instructions.Unreachable(self.block) + self._set_terminator(inst) + return inst + + def atomic_rmw(self, op, ptr, val, ordering, name=''): + inst = instructions.AtomicRMW( + self.block, op, ptr, val, ordering, name=name) + self._insert(inst) + return inst + + def cmpxchg(self, ptr, cmp, val, ordering, failordering=None, name=''): + """ + Atomic compared-and-set: + atomic { + old = *ptr + success = (old == cmp) + if (success) + *ptr = val + } + name = { old, success } + + If failordering is `None`, the value of `ordering` is used. + """ + failordering = ordering if failordering is None else failordering + inst = instructions.CmpXchg(self.block, ptr, cmp, val, ordering, + failordering, name=name) + self._insert(inst) + return inst + + def landingpad(self, typ, name='', cleanup=False): + inst = instructions.LandingPadInstr(self.block, typ, name, cleanup) + self._insert(inst) + return inst + + def assume(self, cond): + """ + Optimizer hint: assume *cond* is always true. + """ + fn = self.module.declare_intrinsic("llvm.assume") + return self.call(fn, [cond]) + + def fence(self, ordering, targetscope=None, name=''): + """ + Add a memory barrier, preventing certain reorderings of load and/or + store accesses with + respect to other processors and devices. + """ + inst = instructions.Fence(self.block, ordering, targetscope, name=name) + self._insert(inst) + return inst + + def comment(self, text): + """ + Puts a single-line comment into the generated IR. This will be ignored + by LLVM, but can be useful for debugging the output of a compiler. Adds + a comment to the source file. + + * *text* is a string that does not contain new line characters. + """ + inst = instructions.Comment(self.block, text) + self._insert(inst) + return inst + + @_uniop_intrinsic_int("llvm.bswap") + def bswap(self, cond): + """ + Used to byte swap integer values with an even number of bytes (positive + multiple of 16 bits) + """ + + @_uniop_intrinsic_int("llvm.bitreverse") + def bitreverse(self, cond): + """ + Reverse the bitpattern of an integer value; for example 0b10110110 + becomes 0b01101101. + """ + + @_uniop_intrinsic_int("llvm.ctpop") + def ctpop(self, cond): + """ + Counts the number of bits set in a value. + """ + + @_uniop_intrinsic_with_flag("llvm.ctlz") + def ctlz(self, cond, flag): + """ + Counts leading zero bits in *value*. Boolean *flag* indicates whether + the result is defined for ``0``. + """ + + @_uniop_intrinsic_with_flag("llvm.cttz") + def cttz(self, cond, flag): + """ + Counts trailing zero bits in *value*. Boolean *flag* indicates whether + the result is defined for ``0``. + """ + + @_triop_intrinsic("llvm.fma") + def fma(self, a, b, c): + """ + Perform the fused multiply-add operation. + """ + + def convert_from_fp16(self, a, to=None, name=''): + """ + Convert from an i16 to the given FP type + """ + if not to: + raise TypeError("expected a float return type") + if not isinstance(to, (types.FloatType, types.DoubleType)): + raise TypeError("expected a float type, got %s" % to) + if not (isinstance(a.type, types.IntType) and a.type.width == 16): + raise TypeError("expected an i16 type, got %s" % a.type) + + opname = 'llvm.convert.from.fp16' + fn = self.module.declare_intrinsic(opname, [to]) + return self.call(fn, [a], name) + + @_uniop_intrinsic_float("llvm.convert.to.fp16") + def convert_to_fp16(self, a): + """ + Convert the given FP number to an i16 + """ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/context.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/context.py new file mode 100644 index 0000000000000000000000000000000000000000..7152e1390fd2fc0819893ae43eefce62f4366472 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/context.py @@ -0,0 +1,20 @@ +from llvmlite.ir import _utils +from llvmlite.ir import types + + +class Context(object): + def __init__(self): + self.scope = _utils.NameScope() + self.identified_types = {} + + def get_identified_type(self, name, packed=False): + if name not in self.identified_types: + self.scope.register(name) + ty = types.IdentifiedStructType(self, name, packed) + self.identified_types[name] = ty + else: + ty = self.identified_types[name] + return ty + + +global_context = Context() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/instructions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/instructions.py new file mode 100644 index 0000000000000000000000000000000000000000..3a13261bda4b24c4763df5fc5bf34889edc75ea6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/instructions.py @@ -0,0 +1,920 @@ +""" +Implementation of LLVM IR instructions. +""" + +from llvmlite.ir import types +from llvmlite.ir.values import (Block, Function, Value, NamedValue, Constant, + MetaDataArgument, MetaDataString, AttributeSet, + Undefined, ArgumentAttributes) +from llvmlite.ir._utils import _HasMetadata + + +class Instruction(NamedValue, _HasMetadata): + def __init__(self, parent, typ, opname, operands, name='', flags=()): + super(Instruction, self).__init__(parent, typ, name=name) + assert isinstance(parent, Block) + assert isinstance(flags, (tuple, list)) + self.opname = opname + self.operands = operands + self.flags = list(flags) + self.metadata = {} + + @property + def function(self): + return self.parent.function + + @property + def module(self): + return self.parent.function.module + + def descr(self, buf): + opname = self.opname + if self.flags: + opname = ' '.join([opname] + self.flags) + operands = ', '.join([op.get_reference() for op in self.operands]) + typ = self.type + metadata = self._stringify_metadata(leading_comma=True) + buf.append("{0} {1} {2}{3}\n" + .format(opname, typ, operands, metadata)) + + def replace_usage(self, old, new): + if old in self.operands: + ops = [] + for op in self.operands: + ops.append(new if op is old else op) + self.operands = tuple(ops) + self._clear_string_cache() + + def __repr__(self): + return "" % ( + self.__class__.__name__, self.name, self.type, + self.opname, self.operands) + + +class CallInstrAttributes(AttributeSet): + _known = frozenset(['convergent', 'noreturn', 'nounwind', 'readonly', + 'readnone', 'noinline', 'alwaysinline']) + + +TailMarkerOptions = frozenset(['tail', 'musttail', 'notail']) + + +class FastMathFlags(AttributeSet): + _known = frozenset(['fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract', + 'afn', 'reassoc']) + + +class CallInstr(Instruction): + def __init__(self, parent, func, args, name='', cconv=None, tail=None, + fastmath=(), attrs=(), arg_attrs=None): + self.cconv = (func.calling_convention + if cconv is None and isinstance(func, Function) + else cconv) + + # For backwards compatibility with previous API of accepting a "truthy" + # value for a hint to the optimizer to potentially tail optimize. + if isinstance(tail, str) and tail in TailMarkerOptions: + pass + elif tail: + tail = "tail" + else: + tail = "" + + self.tail = tail + self.fastmath = FastMathFlags(fastmath) + self.attributes = CallInstrAttributes(attrs) + self.arg_attributes = {} + if arg_attrs: + for idx, attrs in arg_attrs.items(): + if not (0 <= idx < len(args)): + raise ValueError("Invalid argument index {}" + .format(idx)) + self.arg_attributes[idx] = ArgumentAttributes(attrs) + + # Fix and validate arguments + args = list(args) + for i in range(len(func.function_type.args)): + arg = args[i] + expected_type = func.function_type.args[i] + if (isinstance(expected_type, types.MetaDataType) and + arg.type != expected_type): + arg = MetaDataArgument(arg) + if arg.type != expected_type: + msg = ("Type of #{0} arg mismatch: {1} != {2}" + .format(1 + i, expected_type, arg.type)) + raise TypeError(msg) + args[i] = arg + + super(CallInstr, self).__init__(parent, func.function_type.return_type, + "call", [func] + list(args), name=name) + + @property + def callee(self): + return self.operands[0] + + @callee.setter + def callee(self, newcallee): + self.operands[0] = newcallee + + @property + def args(self): + return self.operands[1:] + + def replace_callee(self, newfunc): + if newfunc.function_type != self.callee.function_type: + raise TypeError("New function has incompatible type") + self.callee = newfunc + + @property + def called_function(self): + """The callee function""" + return self.callee + + def _descr(self, buf, add_metadata): + def descr_arg(i, a): + if i in self.arg_attributes: + attrs = ' '.join(self.arg_attributes[i]._to_list(a.type)) + ' ' + else: + attrs = '' + return '{0} {1}{2}'.format(a.type, attrs, a.get_reference()) + args = ', '.join([descr_arg(i, a) for i, a in enumerate(self.args)]) + + fnty = self.callee.function_type + # Only print function type if variable-argument + if fnty.var_arg: + ty = fnty + # Otherwise, just print the return type. + else: + # Fastmath flag work only in this case + ty = fnty.return_type + callee_ref = "{0} {1}".format(ty, self.callee.get_reference()) + if self.cconv: + callee_ref = "{0} {1}".format(self.cconv, callee_ref) + + tail_marker = "" + if self.tail: + tail_marker = "{0} ".format(self.tail) + + fn_attrs = ' ' + ' '.join(self.attributes._to_list(fnty.return_type))\ + if self.attributes else '' + + fm_attrs = ' ' + ' '.join(self.fastmath._to_list(fnty.return_type))\ + if self.fastmath else '' + + buf.append("{tail}{op}{fastmath} {callee}({args}){attr}{meta}\n".format( + tail=tail_marker, + op=self.opname, + callee=callee_ref, + fastmath=fm_attrs, + args=args, + attr=fn_attrs, + meta=(self._stringify_metadata(leading_comma=True) + if add_metadata else ""), + )) + + def descr(self, buf): + self._descr(buf, add_metadata=True) + + +class InvokeInstr(CallInstr): + def __init__(self, parent, func, args, normal_to, unwind_to, name='', + cconv=None, fastmath=(), attrs=(), arg_attrs=None): + assert isinstance(normal_to, Block) + assert isinstance(unwind_to, Block) + super(InvokeInstr, self).__init__(parent, func, args, name, cconv, + tail=False, fastmath=fastmath, + attrs=attrs, arg_attrs=arg_attrs) + self.opname = "invoke" + self.normal_to = normal_to + self.unwind_to = unwind_to + + def descr(self, buf): + super(InvokeInstr, self)._descr(buf, add_metadata=False) + buf.append(" to label {0} unwind label {1}{metadata}\n".format( + self.normal_to.get_reference(), + self.unwind_to.get_reference(), + metadata=self._stringify_metadata(leading_comma=True), + )) + + +class Terminator(Instruction): + def __init__(self, parent, opname, operands): + super(Terminator, self).__init__(parent, types.VoidType(), opname, + operands) + + def descr(self, buf): + opname = self.opname + operands = ', '.join(["{0} {1}".format(op.type, op.get_reference()) + for op in self.operands]) + metadata = self._stringify_metadata(leading_comma=True) + buf.append("{0} {1}{2}".format(opname, operands, metadata)) + + +class PredictableInstr(Instruction): + + def set_weights(self, weights): + operands = [MetaDataString(self.module, "branch_weights")] + for w in weights: + if w < 0: + raise ValueError("branch weight must be a positive integer") + operands.append(Constant(types.IntType(32), w)) + md = self.module.add_metadata(operands) + self.set_metadata("prof", md) + + +class Ret(Terminator): + def __init__(self, parent, opname, return_value=None): + operands = [return_value] if return_value is not None else [] + super(Ret, self).__init__(parent, opname, operands) + + @property + def return_value(self): + if self.operands: + return self.operands[0] + else: + return None + + def descr(self, buf): + return_value = self.return_value + metadata = self._stringify_metadata(leading_comma=True) + if return_value is not None: + buf.append("{0} {1} {2}{3}\n" + .format(self.opname, return_value.type, + return_value.get_reference(), + metadata)) + else: + buf.append("{0}{1}\n".format(self.opname, metadata)) + + +class Branch(Terminator): + pass + + +class ConditionalBranch(PredictableInstr, Terminator): + pass + + +class IndirectBranch(PredictableInstr, Terminator): + def __init__(self, parent, opname, addr): + super(IndirectBranch, self).__init__(parent, opname, [addr]) + self.destinations = [] + + @property + def address(self): + return self.operands[0] + + def add_destination(self, block): + assert isinstance(block, Block) + self.destinations.append(block) + + def descr(self, buf): + destinations = ["label {0}".format(blk.get_reference()) + for blk in self.destinations] + buf.append("indirectbr {0} {1}, [{2}] {3}\n".format( + self.address.type, + self.address.get_reference(), + ', '.join(destinations), + self._stringify_metadata(leading_comma=True), + )) + + +class SwitchInstr(PredictableInstr, Terminator): + + def __init__(self, parent, opname, val, default): + super(SwitchInstr, self).__init__(parent, opname, [val]) + self.default = default + self.cases = [] + + @property + def value(self): + return self.operands[0] + + def add_case(self, val, block): + assert isinstance(block, Block) + if not isinstance(val, Value): + val = Constant(self.value.type, val) + self.cases.append((val, block)) + + def descr(self, buf): + cases = ["{0} {1}, label {2}".format(val.type, val.get_reference(), + blk.get_reference()) + for val, blk in self.cases] + buf.append("switch {0} {1}, label {2} [{3}] {4}\n".format( + self.value.type, + self.value.get_reference(), + self.default.get_reference(), + ' '.join(cases), + self._stringify_metadata(leading_comma=True), + )) + + +class Resume(Terminator): + pass + + +class SelectInstr(Instruction): + def __init__(self, parent, cond, lhs, rhs, name='', flags=()): + assert lhs.type == rhs.type + super(SelectInstr, self).__init__(parent, lhs.type, "select", + [cond, lhs, rhs], name=name, + flags=flags) + + @property + def cond(self): + return self.operands[0] + + @property + def lhs(self): + return self.operands[1] + + @property + def rhs(self): + return self.operands[2] + + def descr(self, buf): + buf.append("select {0} {1} {2}, {3} {4}, {5} {6} {7}\n".format( + ' '.join(self.flags), + self.cond.type, self.cond.get_reference(), + self.lhs.type, self.lhs.get_reference(), + self.rhs.type, self.rhs.get_reference(), + self._stringify_metadata(leading_comma=True), + )) + + +class CompareInstr(Instruction): + # Define the following in subclasses + OPNAME = 'invalid-compare' + VALID_OP = {} + + def __init__(self, parent, op, lhs, rhs, name='', flags=[]): + if op not in self.VALID_OP: + raise ValueError("invalid comparison %r for %s" % (op, self.OPNAME)) + for flag in flags: + if flag not in self.VALID_FLAG: + raise ValueError("invalid flag %r for %s" % (flag, self.OPNAME)) + opname = self.OPNAME + if isinstance(lhs.type, types.VectorType): + typ = types.VectorType(types.IntType(1), lhs.type.count) + else: + typ = types.IntType(1) + super(CompareInstr, self).__init__(parent, typ, + opname, [lhs, rhs], flags=flags, + name=name) + self.op = op + + def descr(self, buf): + buf.append("{opname}{flags} {op} {ty} {lhs}, {rhs} {meta}\n".format( + opname=self.opname, + flags=''.join(' ' + it for it in self.flags), + op=self.op, + ty=self.operands[0].type, + lhs=self.operands[0].get_reference(), + rhs=self.operands[1].get_reference(), + meta=self._stringify_metadata(leading_comma=True), + )) + + +class ICMPInstr(CompareInstr): + OPNAME = 'icmp' + VALID_OP = { + 'eq': 'equal', + 'ne': 'not equal', + 'ugt': 'unsigned greater than', + 'uge': 'unsigned greater or equal', + 'ult': 'unsigned less than', + 'ule': 'unsigned less or equal', + 'sgt': 'signed greater than', + 'sge': 'signed greater or equal', + 'slt': 'signed less than', + 'sle': 'signed less or equal', + } + VALID_FLAG = set() + + +class FCMPInstr(CompareInstr): + OPNAME = 'fcmp' + VALID_OP = { + 'false': 'no comparison, always returns false', + 'oeq': 'ordered and equal', + 'ogt': 'ordered and greater than', + 'oge': 'ordered and greater than or equal', + 'olt': 'ordered and less than', + 'ole': 'ordered and less than or equal', + 'one': 'ordered and not equal', + 'ord': 'ordered (no nans)', + 'ueq': 'unordered or equal', + 'ugt': 'unordered or greater than', + 'uge': 'unordered or greater than or equal', + 'ult': 'unordered or less than', + 'ule': 'unordered or less than or equal', + 'une': 'unordered or not equal', + 'uno': 'unordered (either nans)', + 'true': 'no comparison, always returns true', + } + VALID_FLAG = {'nnan', 'ninf', 'nsz', 'arcp', 'contract', 'afn', 'reassoc', + 'fast'} + + +class CastInstr(Instruction): + def __init__(self, parent, op, val, typ, name=''): + super(CastInstr, self).__init__(parent, typ, op, [val], name=name) + + def descr(self, buf): + buf.append("{0} {1} {2} to {3} {4}\n".format( + self.opname, + self.operands[0].type, + self.operands[0].get_reference(), + self.type, + self._stringify_metadata(leading_comma=True), + )) + + +class LoadInstr(Instruction): + + def __init__(self, parent, ptr, name='', typ=None): + if typ is None: + if isinstance(ptr, AllocaInstr): + typ = ptr.allocated_type + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type.pointee + else: + raise ValueError("Load lacks type.") + super(LoadInstr, self).__init__(parent, typ, "load", [ptr], name=name) + self.align = None + + def descr(self, buf): + [val] = self.operands + if self.align is not None: + align = ', align %d' % (self.align) + else: + align = '' + buf.append("load {0}, {1} {2}{3}{4}\n".format( + self.type, + val.type, + val.get_reference(), + align, + self._stringify_metadata(leading_comma=True), + )) + + +class StoreInstr(Instruction): + def __init__(self, parent, val, ptr): + super(StoreInstr, self).__init__(parent, types.VoidType(), "store", + [val, ptr]) + + def descr(self, buf): + val, ptr = self.operands + if self.align is not None: + align = ', align %d' % (self.align) + else: + align = '' + buf.append("store {0} {1}, {2} {3}{4}{5}\n".format( + val.type, + val.get_reference(), + ptr.type, + ptr.get_reference(), + align, + self._stringify_metadata(leading_comma=True), + )) + + +class LoadAtomicInstr(Instruction): + def __init__(self, parent, ptr, ordering, align, name='', typ=None): + if typ is None: + if isinstance(ptr, AllocaInstr): + typ = ptr.allocated_type + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type.pointee + else: + raise ValueError("Load atomic lacks type.") + super(LoadAtomicInstr, self).__init__(parent, typ, "load atomic", + [ptr], name=name) + self.ordering = ordering + self.align = align + + def descr(self, buf): + [val] = self.operands + buf.append("load atomic {0}, {1} {2} {3}, align {4}{5}\n".format( + self.type, + val.type, + val.get_reference(), + self.ordering, + self.align, + self._stringify_metadata(leading_comma=True), + )) + + +class StoreAtomicInstr(Instruction): + def __init__(self, parent, val, ptr, ordering, align): + super(StoreAtomicInstr, self).__init__(parent, types.VoidType(), + "store atomic", [val, ptr]) + self.ordering = ordering + self.align = align + + def descr(self, buf): + val, ptr = self.operands + buf.append("store atomic {0} {1}, {2} {3} {4}, align {5}{6}\n".format( + val.type, + val.get_reference(), + ptr.type, + ptr.get_reference(), + self.ordering, + self.align, + self._stringify_metadata(leading_comma=True), + )) + + +class AllocaInstr(Instruction): + def __init__(self, parent, typ, count, name): + operands = [count] if count else () + super(AllocaInstr, self).__init__(parent, typ.as_pointer(), "alloca", + operands, name) + self.allocated_type = typ + self.align = None + + def descr(self, buf): + buf.append("{0} {1}".format(self.opname, self.allocated_type)) + if self.operands: + op, = self.operands + buf.append(", {0} {1}".format(op.type, op.get_reference())) + if self.align is not None: + buf.append(", align {0}".format(self.align)) + if self.metadata: + buf.append(self._stringify_metadata(leading_comma=True)) + + +class GEPInstr(Instruction): + def __init__(self, parent, ptr, indices, inbounds, name, + source_etype=None): + if source_etype is not None: + typ = ptr.type + self.source_etype = source_etype + # For compatibility with typed pointers. Eventually this should + # probably be removed (when typed pointers are fully removed). + elif not ptr.type.is_opaque: + typ = ptr.type + lasttyp = None + lastaddrspace = 0 + for i in indices: + lasttyp, typ = typ, typ.gep(i) + # inherit the addrspace from the last seen pointer + if isinstance(lasttyp, types.PointerType): + lastaddrspace = lasttyp.addrspace + + if (not isinstance(typ, types.PointerType) and + isinstance(lasttyp, types.PointerType)): + typ = lasttyp + else: + typ = typ.as_pointer(lastaddrspace) + self.source_etype = ptr.type.pointee + else: + raise ValueError("GEP lacks type.") + super(GEPInstr, self).__init__(parent, typ, "getelementptr", + [ptr] + list(indices), name=name) + self.pointer = ptr + self.indices = indices + self.inbounds = inbounds + + def descr(self, buf): + indices = ['{0} {1}'.format(i.type, i.get_reference()) + for i in self.indices] + op = "getelementptr inbounds" if self.inbounds else "getelementptr" + buf.append("{0} {1}, {2} {3}, {4} {5}\n".format( + op, + self.source_etype, + self.pointer.type, + self.pointer.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class PhiInstr(Instruction): + def __init__(self, parent, typ, name, flags=()): + super(PhiInstr, self).__init__(parent, typ, "phi", (), name=name, + flags=flags) + self.incomings = [] + + def descr(self, buf): + incs = ', '.join('[{0}, {1}]'.format(v.get_reference(), + b.get_reference()) + for v, b in self.incomings) + buf.append("phi {0} {1} {2} {3}\n".format( + ' '.join(self.flags), + self.type, + incs, + self._stringify_metadata(leading_comma=True), + )) + + def add_incoming(self, value, block): + assert isinstance(block, Block) + self.incomings.append((value, block)) + + def replace_usage(self, old, new): + self.incomings = [((new if val is old else val), blk) + for (val, blk) in self.incomings] + + +class ExtractElement(Instruction): + def __init__(self, parent, vector, index, name=''): + if not isinstance(vector.type, types.VectorType): + raise TypeError("vector needs to be of VectorType.") + if not isinstance(index.type, types.IntType): + raise TypeError("index needs to be of IntType.") + typ = vector.type.element + super(ExtractElement, self).__init__(parent, typ, "extractelement", + [vector, index], name=name) + + def descr(self, buf): + operands = ", ".join("{0} {1}".format( + op.type, op.get_reference()) for op in self.operands) + buf.append("{opname} {operands}\n".format( + opname=self.opname, operands=operands)) + + +class InsertElement(Instruction): + def __init__(self, parent, vector, value, index, name=''): + if not isinstance(vector.type, types.VectorType): + raise TypeError("vector needs to be of VectorType.") + if not value.type == vector.type.element: + raise TypeError( + "value needs to be of type {} not {}.".format( + vector.type.element, value.type)) + if not isinstance(index.type, types.IntType): + raise TypeError("index needs to be of IntType.") + typ = vector.type + super(InsertElement, self).__init__(parent, typ, "insertelement", + [vector, value, index], name=name) + + def descr(self, buf): + operands = ", ".join("{0} {1}".format( + op.type, op.get_reference()) for op in self.operands) + buf.append("{opname} {operands}\n".format( + opname=self.opname, operands=operands)) + + +class ShuffleVector(Instruction): + def __init__(self, parent, vector1, vector2, mask, name=''): + if not isinstance(vector1.type, types.VectorType): + raise TypeError("vector1 needs to be of VectorType.") + if vector2 != Undefined: + if vector2.type != vector1.type: + raise TypeError("vector2 needs to be " + + "Undefined or of the same type as vector1.") + if (not isinstance(mask, Constant) or + not isinstance(mask.type, types.VectorType) or + not (isinstance(mask.type.element, types.IntType) and + mask.type.element.width == 32)): + raise TypeError("mask needs to be a constant i32 vector.") + typ = types.VectorType(vector1.type.element, mask.type.count) + index_range = range(vector1.type.count + if vector2 == Undefined + else 2 * vector1.type.count) + if not all(ii.constant in index_range for ii in mask.constant): + raise IndexError( + "mask values need to be in {0}".format(index_range), + ) + super(ShuffleVector, self).__init__(parent, typ, "shufflevector", + [vector1, vector2, mask], name=name) + + def descr(self, buf): + buf.append("shufflevector {0} {1}\n".format( + ", ".join("{0} {1}".format(op.type, op.get_reference()) + for op in self.operands), + self._stringify_metadata(leading_comma=True), + )) + + +class ExtractValue(Instruction): + def __init__(self, parent, agg, indices, name=''): + typ = agg.type + try: + for i in indices: + typ = typ.elements[i] + except (AttributeError, IndexError): + raise TypeError("Can't index at %r in %s" + % (list(indices), agg.type)) + + super(ExtractValue, self).__init__(parent, typ, "extractvalue", + [agg], name=name) + + self.aggregate = agg + self.indices = indices + + def descr(self, buf): + indices = [str(i) for i in self.indices] + + buf.append("extractvalue {0} {1}, {2} {3}\n".format( + self.aggregate.type, + self.aggregate.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class InsertValue(Instruction): + def __init__(self, parent, agg, elem, indices, name=''): + typ = agg.type + try: + for i in indices: + typ = typ.elements[i] + except (AttributeError, IndexError): + raise TypeError("Can't index at %r in %s" + % (list(indices), agg.type)) + if elem.type != typ: + raise TypeError("Can only insert %s at %r in %s: got %s" + % (typ, list(indices), agg.type, elem.type)) + super(InsertValue, self).__init__(parent, agg.type, "insertvalue", + [agg, elem], name=name) + + self.aggregate = agg + self.value = elem + self.indices = indices + + def descr(self, buf): + indices = [str(i) for i in self.indices] + + buf.append("insertvalue {0} {1}, {2} {3}, {4} {5}\n".format( + self.aggregate.type, self.aggregate.get_reference(), + self.value.type, self.value.get_reference(), + ', '.join(indices), + self._stringify_metadata(leading_comma=True), + )) + + +class Unreachable(Instruction): + def __init__(self, parent): + super(Unreachable, self).__init__(parent, types.VoidType(), + "unreachable", (), name='') + + def descr(self, buf): + buf += (self.opname, "\n") + + +class InlineAsm(object): + def __init__(self, ftype, asm, constraint, side_effect=False): + self.type = ftype.return_type + self.function_type = ftype + self.asm = asm + self.constraint = constraint + self.side_effect = side_effect + + def descr(self, buf): + sideeffect = 'sideeffect' if self.side_effect else '' + fmt = 'asm {sideeffect} "{asm}", "{constraint}"' + buf.append(fmt.format(sideeffect=sideeffect, asm=self.asm, + constraint=self.constraint)) + + def get_reference(self): + buf = [] + self.descr(buf) + return "".join(buf) + + def __str__(self): + return "{0} {1}".format(self.type, self.get_reference()) + + +class AtomicRMW(Instruction): + def __init__(self, parent, op, ptr, val, ordering, name): + super(AtomicRMW, self).__init__(parent, val.type, "atomicrmw", + (ptr, val), name=name) + self.operation = op + self.ordering = ordering + + def descr(self, buf): + ptr, val = self.operands + fmt = ("atomicrmw {op} {ptrty} {ptr}, {valty} {val} {ordering} " + "{metadata}\n") + buf.append(fmt.format(op=self.operation, + ptrty=ptr.type, + ptr=ptr.get_reference(), + valty=val.type, + val=val.get_reference(), + ordering=self.ordering, + metadata=self._stringify_metadata( + leading_comma=True), + )) + + +class CmpXchg(Instruction): + """This instruction has changed since llvm3.5. It is not compatible with + older llvm versions. + """ + + def __init__(self, parent, ptr, cmp, val, ordering, failordering, name): + outtype = types.LiteralStructType([val.type, types.IntType(1)]) + super(CmpXchg, self).__init__(parent, outtype, "cmpxchg", + (ptr, cmp, val), name=name) + self.ordering = ordering + self.failordering = failordering + + def descr(self, buf): + ptr, cmpval, val = self.operands + fmt = "cmpxchg {ptrty} {ptr}, {ty} {cmp}, {ty} {val} {ordering} " \ + "{failordering} {metadata}\n" + buf.append(fmt.format(ptrty=ptr.type, + ptr=ptr.get_reference(), + ty=cmpval.type, + cmp=cmpval.get_reference(), + val=val.get_reference(), + ordering=self.ordering, + failordering=self.failordering, + metadata=self._stringify_metadata( + leading_comma=True), + )) + + +class _LandingPadClause(object): + def __init__(self, value): + self.value = value + + def __str__(self): + return "{kind} {type} {value}".format( + kind=self.kind, + type=self.value.type, + value=self.value.get_reference()) + + +class CatchClause(_LandingPadClause): + kind = 'catch' + + +class FilterClause(_LandingPadClause): + kind = 'filter' + + def __init__(self, value): + assert isinstance(value, Constant) + assert isinstance(value.type, types.ArrayType) + super(FilterClause, self).__init__(value) + + +class LandingPadInstr(Instruction): + def __init__(self, parent, typ, name='', cleanup=False): + super(LandingPadInstr, self).__init__(parent, typ, "landingpad", [], + name=name) + self.cleanup = cleanup + self.clauses = [] + + def add_clause(self, clause): + assert isinstance(clause, _LandingPadClause) + self.clauses.append(clause) + + def descr(self, buf): + fmt = "landingpad {type}{cleanup}{clauses}\n" + buf.append(fmt.format(type=self.type, + cleanup=' cleanup' if self.cleanup else '', + clauses=''.join(["\n {0}".format(clause) + for clause in self.clauses]), + )) + + +class Fence(Instruction): + """ + The `fence` instruction. + + As of LLVM 5.0.1: + + fence [syncscope("")] ; yields void + """ + + VALID_FENCE_ORDERINGS = {"acquire", "release", "acq_rel", "seq_cst"} + + def __init__(self, parent, ordering, targetscope=None, name=''): + super(Fence, self).__init__(parent, types.VoidType(), "fence", (), + name=name) + if ordering not in self.VALID_FENCE_ORDERINGS: + msg = "Invalid fence ordering \"{0}\"! Should be one of {1}." + raise ValueError(msg .format(ordering, + ", ".join(self.VALID_FENCE_ORDERINGS))) + self.ordering = ordering + self.targetscope = targetscope + + def descr(self, buf): + if self.targetscope is None: + syncscope = "" + else: + syncscope = 'syncscope("{0}") '.format(self.targetscope) + + fmt = "fence {syncscope}{ordering}\n" + buf.append(fmt.format(syncscope=syncscope, + ordering=self.ordering, + )) + + +class Comment(Instruction): + """ + A line comment. + """ + + def __init__(self, parent, text): + super(Comment, self).__init__(parent, types.VoidType(), ";", (), + name='') + assert "\n" not in text, "Comment cannot contain new line" + self.text = text + + def descr(self, buf): + buf.append(f"; {self.text}") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/module.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/module.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7eeca67aedc203f77bf47771d9ccb55300ea17 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/module.py @@ -0,0 +1,256 @@ +import collections + +from llvmlite.ir import context, values, types, _utils + + +class Module(object): + def __init__(self, name='', context=context.global_context): + self.context = context + self.name = name # name is for debugging/informational + self.data_layout = "" + self.scope = _utils.NameScope() + self.triple = 'unknown-unknown-unknown' + self.globals = collections.OrderedDict() + # Innamed metadata nodes. + self.metadata = [] + # Named metadata nodes + self.namedmetadata = {} + # Cache for metadata node deduplication + self._metadatacache = {} + + def _fix_metadata_operands(self, operands): + fixed_ops = [] + for op in operands: + if op is None: + # A literal None creates a null metadata value + op = types.MetaDataType()(None) + elif isinstance(op, str): + # A literal string creates a metadata string value + op = values.MetaDataString(self, op) + elif isinstance(op, (list, tuple)): + # A sequence creates a metadata node reference + op = self.add_metadata(op) + fixed_ops.append(op) + return fixed_ops + + def _fix_di_operands(self, operands): + fixed_ops = [] + for name, op in operands: + if isinstance(op, (list, tuple)): + # A sequence creates a metadata node reference + op = self.add_metadata(op) + fixed_ops.append((name, op)) + return fixed_ops + + def str_ditok_operands(self, operands): + str_ops = [] + for name, op in operands: + if name == 'encoding' and isinstance(op, values.DIToken): + # use string value instead of address of object + op = op.value + str_ops.append((name, op)) + return str_ops + + def add_metadata(self, operands): + """ + Add an unnamed metadata to the module with the given *operands* + (a sequence of values) or return a previous equivalent metadata. + A MDValue instance is returned, it can then be associated to + e.g. an instruction. + """ + if not isinstance(operands, (list, tuple)): + raise TypeError("expected a list or tuple of metadata values, " + "got %r" % (operands,)) + operands = self._fix_metadata_operands(operands) + key = tuple(operands) + if key not in self._metadatacache: + n = len(self.metadata) + md = values.MDValue(self, operands, name=str(n)) + self._metadatacache[key] = md + else: + md = self._metadatacache[key] + return md + + def add_debug_info(self, kind, operands, is_distinct=False): + """ + Add debug information metadata to the module with the given + *operands* (a dict of values with string keys) or return + a previous equivalent metadata. *kind* is a string of the + debug information kind (e.g. "DICompileUnit"). + + A DIValue instance is returned, it can then be associated to e.g. + an instruction. + """ + operands = tuple(sorted(self._fix_di_operands(operands.items()))) + str_op_key = tuple(sorted(self.str_ditok_operands(operands))) + key = (kind, str_op_key, is_distinct) + if key not in self._metadatacache: + n = len(self.metadata) + di = values.DIValue(self, is_distinct, kind, operands, name=str(n)) + self._metadatacache[key] = di + else: + di = self._metadatacache[key] + return di + + def add_named_metadata(self, name, element=None): + """ + Add a named metadata node to the module, if it doesn't exist, + or return the existing node. + If *element* is given, it will append a new element to + the named metadata node. If *element* is a sequence of values + (rather than a metadata value), a new unnamed node will first be + created. + + Example:: + module.add_named_metadata("llvm.ident", ["llvmlite/1.0"]) + """ + if name in self.namedmetadata: + nmd = self.namedmetadata[name] + else: + nmd = self.namedmetadata[name] = values.NamedMetaData(self) + if element is not None: + if not isinstance(element, values.Value): + element = self.add_metadata(element) + if not isinstance(element.type, types.MetaDataType): + raise TypeError("wrong type for metadata element: got %r" + % (element,)) + nmd.add(element) + return nmd + + def get_named_metadata(self, name): + """ + Return the metadata node with the given *name*. KeyError is raised + if no such node exists (contrast with add_named_metadata()). + """ + return self.namedmetadata[name] + + @property + def functions(self): + """ + A list of functions declared or defined in this module. + """ + return [v for v in self.globals.values() + if isinstance(v, values.Function)] + + @property + def global_values(self): + """ + An iterable of global values in this module. + """ + return self.globals.values() + + def get_global(self, name): + """ + Get a global value by name. + """ + return self.globals[name] + + def add_global(self, globalvalue): + """ + Add a new global value. + """ + assert globalvalue.name not in self.globals + self.globals[globalvalue.name] = globalvalue + + def get_unique_name(self, name=''): + """ + Get a unique global name with the following *name* hint. + """ + return self.scope.deduplicate(name) + + def declare_intrinsic(self, intrinsic, tys=(), fnty=None): + def _error(): + raise NotImplementedError("unknown intrinsic %r with %d types" + % (intrinsic, len(tys))) + + if intrinsic in {'llvm.cttz', 'llvm.ctlz', 'llvm.fma'}: + suffixes = [tys[0].intrinsic_name] + else: + suffixes = [t.intrinsic_name for t in tys] + name = '.'.join([intrinsic] + suffixes) + if name in self.globals: + return self.globals[name] + + if fnty is not None: + # General case: function type is given + pass + # Compute function type if omitted for common cases + elif len(tys) == 0 and intrinsic == 'llvm.assume': + fnty = types.FunctionType(types.VoidType(), [types.IntType(1)]) + elif len(tys) == 1: + if intrinsic == 'llvm.powi': + fnty = types.FunctionType(tys[0], [tys[0], types.IntType(32)]) + elif intrinsic == 'llvm.pow': + fnty = types.FunctionType(tys[0], tys * 2) + elif intrinsic == 'llvm.convert.from.fp16': + fnty = types.FunctionType(tys[0], [types.IntType(16)]) + elif intrinsic == 'llvm.convert.to.fp16': + fnty = types.FunctionType(types.IntType(16), tys) + else: + fnty = types.FunctionType(tys[0], tys) + elif len(tys) == 2: + if intrinsic == 'llvm.memset': + tys = [tys[0], types.IntType(8), tys[1], + types.IntType(1)] + fnty = types.FunctionType(types.VoidType(), tys) + elif intrinsic in {'llvm.cttz', 'llvm.ctlz'}: + tys = [tys[0], types.IntType(1)] + fnty = types.FunctionType(tys[0], tys) + else: + _error() + elif len(tys) == 3: + if intrinsic in ('llvm.memcpy', 'llvm.memmove'): + tys = tys + [types.IntType(1)] + fnty = types.FunctionType(types.VoidType(), tys) + elif intrinsic == 'llvm.fma': + tys = [tys[0]] * 3 + fnty = types.FunctionType(tys[0], tys) + else: + _error() + else: + _error() + return values.Function(self, fnty, name=name) + + def get_identified_types(self): + return self.context.identified_types + + def _get_body_lines(self): + # Type declarations + lines = [it.get_declaration() + for it in self.get_identified_types().values()] + # Global values (including function definitions) + lines += [str(v) for v in self.globals.values()] + return lines + + def _get_metadata_lines(self): + mdbuf = [] + for k, v in self.namedmetadata.items(): + mdbuf.append("!{name} = !{{ {operands} }}".format( + name=k, operands=', '.join(i.get_reference() + for i in v.operands))) + for md in self.metadata: + mdbuf.append(str(md)) + return mdbuf + + def _stringify_body(self): + # For testing + return "\n".join(self._get_body_lines()) + + def _stringify_metadata(self): + # For testing + return "\n".join(self._get_metadata_lines()) + + def __repr__(self): + lines = [] + # Header + lines += [ + '; ModuleID = "%s"' % (self.name,), + 'target triple = "%s"' % (self.triple,), + 'target datalayout = "%s"' % (self.data_layout,), + ''] + # Body + lines += self._get_body_lines() + # Metadata + lines += self._get_metadata_lines() + + return "\n".join(lines) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/transforms.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..a69113d36e93b6b9e42a2a15119697375cff62e5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/transforms.py @@ -0,0 +1,64 @@ +from llvmlite.ir import CallInstr + + +class Visitor(object): + def visit(self, module): + self._module = module + for func in module.functions: + self.visit_Function(func) + + def visit_Function(self, func): + self._function = func + for bb in func.blocks: + self.visit_BasicBlock(bb) + + def visit_BasicBlock(self, bb): + self._basic_block = bb + for instr in bb.instructions: + self.visit_Instruction(instr) + + def visit_Instruction(self, instr): + raise NotImplementedError + + @property + def module(self): + return self._module + + @property + def function(self): + return self._function + + @property + def basic_block(self): + return self._basic_block + + +class CallVisitor(Visitor): + def visit_Instruction(self, instr): + if isinstance(instr, CallInstr): + self.visit_Call(instr) + + def visit_Call(self, instr): + raise NotImplementedError + + +class ReplaceCalls(CallVisitor): + def __init__(self, orig, repl): + super(ReplaceCalls, self).__init__() + self.orig = orig + self.repl = repl + self.calls = [] + + def visit_Call(self, instr): + if instr.callee == self.orig: + instr.replace_callee(self.repl) + self.calls.append(instr) + + +def replace_all_calls(mod, orig, repl): + """Replace all calls to `orig` to `repl` in module `mod`. + Returns the references to the returned calls + """ + rc = ReplaceCalls(orig, repl) + rc.visit(mod) + return rc.calls diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/types.py new file mode 100644 index 0000000000000000000000000000000000000000..8013918cf46ec6c070a4655fe076719ee2d8d8a7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/types.py @@ -0,0 +1,732 @@ +""" +Classes that are LLVM types +""" + +import struct + +from llvmlite import ir_layer_typed_pointers_enabled +from llvmlite.ir._utils import _StrCaching + + +def _wrapname(x): + return '"{0}"'.format(x.replace('\\', '\\5c').replace('"', '\\22')) + + +class Type(_StrCaching): + """ + The base class for all LLVM types. + """ + is_pointer = False + null = 'zeroinitializer' + + def __repr__(self): + return "<%s %s>" % (type(self), str(self)) + + def _to_string(self): + raise NotImplementedError + + def as_pointer(self, addrspace=0): + return PointerType(self, addrspace) + + def __ne__(self, other): + return not (self == other) + + def _get_ll_global_value_type(self, target_data, context=None): + """ + Convert this type object to an LLVM type. + """ + from llvmlite.ir import Module, GlobalVariable + from llvmlite.binding import parse_assembly + + if context is None: + m = Module() + else: + m = Module(context=context) + foo = GlobalVariable(m, self, name="foo") + with parse_assembly(str(m)) as llmod: + return llmod.get_global_variable(foo.name).global_value_type + + def get_abi_size(self, target_data, context=None): + """ + Get the ABI size of this type according to data layout *target_data*. + """ + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_abi_size(llty) + + def get_element_offset(self, target_data, ndx, context=None): + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_element_offset(llty, ndx) + + def get_abi_alignment(self, target_data, context=None): + """ + Get the minimum ABI alignment of this type according to data layout + *target_data*. + """ + llty = self._get_ll_global_value_type(target_data, context) + return target_data.get_abi_alignment(llty) + + def format_constant(self, value): + """ + Format constant *value* of this type. This method may be overriden + by subclasses. + """ + return str(value) + + def wrap_constant_value(self, value): + """ + Wrap constant *value* if necessary. This method may be overriden + by subclasses (especially aggregate types). + """ + return value + + def __call__(self, value): + """ + Create a LLVM constant of this type with the given Python value. + """ + from llvmlite.ir import Constant + return Constant(self, value) + + +class MetaDataType(Type): + + def _to_string(self): + return "metadata" + + def as_pointer(self): + raise TypeError + + def __eq__(self, other): + return isinstance(other, MetaDataType) + + def __hash__(self): + return hash(MetaDataType) + + +class LabelType(Type): + """ + The label type is the type of e.g. basic blocks. + """ + + def _to_string(self): + return "label" + + +class PointerType(Type): + """ + The type of all pointer values. + By default (without specialisation) represents an opaque pointer. + """ + is_opaque = True + is_pointer = True + null = 'null' + + # Factory to create typed or opaque pointers based on `pointee'. + def __new__(cls, pointee=None, addrspace=0): + if cls is PointerType and pointee is not None and \ + type(pointee) is not PointerType: + return super().__new__(_TypedPointerType) + return super(PointerType, cls).__new__(cls) + + def __init__(self, pointee=None, addrspace=0): + assert pointee is None or type(pointee) is PointerType + self.addrspace = addrspace + + def _to_string(self): + if self.addrspace != 0: + return "ptr addrspace({0})".format(self.addrspace) + else: + return "ptr" + + def __eq__(self, other): + return (isinstance(other, PointerType) and + self.addrspace == other.addrspace) + + def __hash__(self): + return hash(PointerType) + + @property + def intrinsic_name(self): + return 'p%d' % self.addrspace + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return cls() + + +class _TypedPointerType(PointerType): + """ + The type of typed pointer values. To be removed eventually. + """ + + def __init__(self, pointee, addrspace=0): + super(_TypedPointerType, self).__init__(None, addrspace) + assert pointee is not None and type(pointee) is not PointerType + assert not isinstance(pointee, VoidType) + self.pointee = pointee + self.is_opaque = False + + def _to_string(self): + if ir_layer_typed_pointers_enabled: + return "{0}*".format(self.pointee) if self.addrspace == 0 else \ + "{0} addrspace({1})*".format(self.pointee, self.addrspace) + return super(_TypedPointerType, self)._to_string() + + # This implements ``isOpaqueOrPointeeTypeEquals''. + def __eq__(self, other): + if isinstance(other, _TypedPointerType): + return (self.pointee, self.addrspace) == (other.pointee, + other.addrspace) + return (isinstance(other, PointerType) and + self.addrspace == other.addrspace) + + def __hash__(self): + return hash(_TypedPointerType) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.pointee + + @property + def intrinsic_name(self): + if ir_layer_typed_pointers_enabled: + return 'p%d%s' % (self.addrspace, self.pointee.intrinsic_name) + return super(_TypedPointerType, self).intrinsic_name + + +class VoidType(Type): + """ + The type for empty values (e.g. a function returning no value). + """ + + def _to_string(self): + return 'void' + + def __eq__(self, other): + return isinstance(other, VoidType) + + def __hash__(self): + return hash(VoidType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return cls() + + +class FunctionType(Type): + """ + The type for functions. + """ + + def __init__(self, return_type, args, var_arg=False): + self.return_type = return_type + self.args = tuple(args) + self.var_arg = var_arg + + def _to_string(self): + if self.args: + strargs = ', '.join([str(a) for a in self.args]) + if self.var_arg: + return '{0} ({1}, ...)'.format(self.return_type, strargs) + else: + return '{0} ({1})'.format(self.return_type, strargs) + elif self.var_arg: + return '{0} (...)'.format(self.return_type) + else: + return '{0} ()'.format(self.return_type) + + def __eq__(self, other): + if isinstance(other, FunctionType): + return (self.return_type == other.return_type and + self.args == other.args and self.var_arg == other.var_arg) + else: + return False + + def __hash__(self): + return hash(FunctionType) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + params = tuple(x.as_ir(ir_ctx=ir_ctx) + for x in typeref.get_function_parameters()) + ret = typeref.get_function_return().as_ir(ir_ctx=ir_ctx) + is_vararg = typeref.is_function_vararg + return cls(ret, params, is_vararg) + + +class IntType(Type): + """ + The type for integers. + """ + null = '0' + _instance_cache = {} + width: int + + def __new__(cls, bits): + # Cache all common integer types + if 0 <= bits <= 128: + try: + return cls._instance_cache[bits] + except KeyError: + inst = cls._instance_cache[bits] = cls.__new(bits) + return inst + return cls.__new(bits) + + @classmethod + def __new(cls, bits): + assert isinstance(bits, int) and bits >= 0 + self = super(IntType, cls).__new__(cls) + self.width = bits + return self + + def __getnewargs__(self): + return self.width, + + def __copy__(self): + return self + + def _to_string(self): + return 'i%u' % (self.width,) + + def __eq__(self, other): + if isinstance(other, IntType): + return self.width == other.width + else: + return False + + def __hash__(self): + return hash(IntType) + + def format_constant(self, val): + if isinstance(val, bool): + return str(val).lower() + else: + return str(val) + + def wrap_constant_value(self, val): + if val is None: + return 0 + return val + + @property + def intrinsic_name(self): + return str(self) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return IntType(typeref.type_width) + + +def _as_float(value): + """ + Truncate to single-precision float. + """ + return struct.unpack('f', struct.pack('f', value))[0] + + +def _as_half(value): + """ + Truncate to half-precision float. + """ + try: + return struct.unpack('e', struct.pack('e', value))[0] + except struct.error: + # 'e' only added in Python 3.6+ + return _as_float(value) + + +def _format_float_as_hex(value, packfmt, unpackfmt, numdigits): + raw = struct.pack(packfmt, float(value)) + intrep = struct.unpack(unpackfmt, raw)[0] + out = '{{0:#{0}x}}'.format(numdigits).format(intrep) + return out + + +def _format_double(value): + """ + Format *value* as a hexadecimal string of its IEEE double precision + representation. + """ + return _format_float_as_hex(value, 'd', 'Q', 16) + + +class _BaseFloatType(Type): + + def __new__(cls): + return cls._instance_cache + + def __eq__(self, other): + return isinstance(other, type(self)) + + def __hash__(self): + return hash(type(self)) + + @classmethod + def _create_instance(cls): + cls._instance_cache = super(_BaseFloatType, cls).__new__(cls) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + return cls() + + +class HalfType(_BaseFloatType): + """ + The type for single-precision floats. + """ + null = '0.0' + intrinsic_name = 'f16' + + def __str__(self): + return 'half' + + def format_constant(self, value): + return _format_double(_as_half(value)) + + +class FloatType(_BaseFloatType): + """ + The type for single-precision floats. + """ + null = '0.0' + intrinsic_name = 'f32' + + def __str__(self): + return 'float' + + def format_constant(self, value): + return _format_double(_as_float(value)) + + +class DoubleType(_BaseFloatType): + """ + The type for double-precision floats. + """ + null = '0.0' + intrinsic_name = 'f64' + + def __str__(self): + return 'double' + + def format_constant(self, value): + return _format_double(value) + + +for _cls in (HalfType, FloatType, DoubleType): + _cls._create_instance() + + +class _Repeat(object): + def __init__(self, value, size): + self.value = value + self.size = size + + def __len__(self): + return self.size + + def __getitem__(self, item): + if 0 <= item < self.size: + return self.value + else: + raise IndexError(item) + + +class VectorType(Type): + """ + The type for vectors of primitive data items (e.g. ""). + """ + + def __init__(self, element, count): + self.element = element + self.count = count + + @property + def elements(self): + return _Repeat(self.element, self.count) + + def __len__(self): + return self.count + + def _to_string(self): + return "<%d x %s>" % (self.count, self.element) + + def __eq__(self, other): + if isinstance(other, VectorType): + return self.element == other.element and self.count == other.count + + def __hash__(self): + # TODO: why does this not take self.element/self.count into account? + return hash(VectorType) + + def __copy__(self): + return self + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + return "<{0}>".format(itemstring) + + def wrap_constant_value(self, values): + from . import Value, Constant + if not isinstance(values, (list, tuple)): + if isinstance(values, Constant): + if values.type != self.element: + raise TypeError("expected {} for {}".format( + self.element, values.type)) + return (values, ) * self.count + return (Constant(self.element, values), ) * self.count + if len(values) != len(self): + raise ValueError("wrong constant size for %s: got %d elements" + % (self, len(values))) + return [Constant(ty, val) if not isinstance(val, Value) else val + for ty, val in zip(self.elements, values)] + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + [elemtyperef] = typeref.elements + elemty = elemtyperef.as_ir(ir_ctx=ir_ctx) + count = typeref.element_count + return cls(elemty, count) + + +class Aggregate(Type): + """ + Base class for aggregate types. + See http://llvm.org/docs/LangRef.html#t-aggregate + """ + + def wrap_constant_value(self, values): + from . import Value, Constant + + if not isinstance(values, (list, tuple)): + return values + if len(values) != len(self): + raise ValueError("wrong constant size for %s: got %d elements" + % (self, len(values))) + return [Constant(ty, val) if not isinstance(val, Value) else val + for ty, val in zip(self.elements, values)] + + +class ArrayType(Aggregate): + """ + The type for fixed-size homogenous arrays (e.g. "[f32 x 3]"). + """ + + def __init__(self, element, count): + self.element = element + self.count = count + + @property + def elements(self): + return _Repeat(self.element, self.count) + + def __len__(self): + return self.count + + def _to_string(self): + return "[%d x %s]" % (self.count, self.element) + + def __eq__(self, other): + if isinstance(other, ArrayType): + return self.element == other.element and self.count == other.count + + def __hash__(self): + return hash(ArrayType) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.element + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + return "[{0}]".format(itemstring) + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + [elemtyperef] = typeref.elements + elemty = elemtyperef.as_ir(ir_ctx=ir_ctx) + count = typeref.element_count + return cls(elemty, count) + + +class BaseStructType(Aggregate): + """ + The base type for heterogenous struct types. + """ + _packed = False + + @property + def packed(self): + """ + A boolean attribute that indicates whether the structure uses + packed layout. + """ + return self._packed + + @packed.setter + def packed(self, val): + self._packed = bool(val) + + def __len__(self): + assert self.elements is not None + return len(self.elements) + + def __iter__(self): + assert self.elements is not None + return iter(self.elements) + + @property + def is_opaque(self): + return self.elements is None + + def structure_repr(self): + """ + Return the LLVM IR for the structure representation + """ + ret = '{%s}' % ', '.join([str(x) for x in self.elements]) + return self._wrap_packed(ret) + + def format_constant(self, value): + itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference()) + for x in value]) + ret = "{{{0}}}".format(itemstring) + return self._wrap_packed(ret) + + def gep(self, i): + """ + Resolve the type of the i-th element (for getelementptr lookups). + + *i* needs to be a LLVM constant, so that the type can be determined + at compile-time. + """ + if not isinstance(i.type, IntType): + raise TypeError(i.type) + return self.elements[i.constant] + + def _wrap_packed(self, textrepr): + """ + Internal helper to wrap textual repr of struct type into packed struct + """ + if self.packed: + return '<{}>'.format(textrepr) + else: + return textrepr + + @classmethod + def from_llvm(cls, typeref, ir_ctx): + """ + Create from a llvmlite.binding.TypeRef + """ + if typeref.is_literal_struct: + elems = [el.as_ir(ir_ctx=ir_ctx) for el in typeref.elements] + return cls(elems, typeref.is_packed_struct) + else: + return ir_ctx.get_identified_type(typeref.name) + + +class LiteralStructType(BaseStructType): + """ + The type of "literal" structs, i.e. structs with a literally-defined + type (by contrast with IdentifiedStructType). + """ + + null = 'zeroinitializer' + + def __init__(self, elems, packed=False): + """ + *elems* is a sequence of types to be used as members. + *packed* controls the use of packed layout. + """ + self.elements = tuple(elems) + self.packed = packed + + def _to_string(self): + return self.structure_repr() + + def __eq__(self, other): + if isinstance(other, LiteralStructType): + return (self.elements == other.elements + and self.packed == other.packed) + + def __hash__(self): + return hash(LiteralStructType) + + +class IdentifiedStructType(BaseStructType): + """ + A type which is a named alias for another struct type, akin to a typedef. + While literal struct types can be structurally equal (see + LiteralStructType), identified struct types are compared by name. + + Do not use this directly. + """ + null = 'zeroinitializer' + + def __init__(self, context, name, packed=False): + """ + *context* is a llvmlite.ir.Context. + *name* is the identifier for the new struct type. + *packed* controls the use of packed layout. + """ + assert name + self.context = context + self.name = name + self.elements = None + self.packed = packed + + def _to_string(self): + return "%{name}".format(name=_wrapname(self.name)) + + def get_declaration(self): + """ + Returns the string for the declaration of the type + """ + if self.is_opaque: + out = "{strrep} = type opaque".format(strrep=str(self)) + else: + out = "{strrep} = type {struct}".format( + strrep=str(self), struct=self.structure_repr()) + return out + + def __eq__(self, other): + if isinstance(other, IdentifiedStructType): + return (self.name == other.name + and self.packed == other.packed) + + def __hash__(self): + return hash(IdentifiedStructType) + + def set_body(self, *elems): + if not self.is_opaque: + raise RuntimeError("{name} is already defined".format( + name=self.name)) + self.elements = tuple(elems) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/values.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/values.py new file mode 100644 index 0000000000000000000000000000000000000000..7aaa18c06ea01b15c99eac26db7fa9ffe1a3746b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/ir/values.py @@ -0,0 +1,1221 @@ +""" +Classes that are LLVM values: Value, Constant... +Instructions are in the instructions module. +""" + +import functools +import string +import re +from types import MappingProxyType + +from llvmlite.ir import values, types, _utils +from llvmlite.ir._utils import (_StrCaching, _StringReferenceCaching, + _HasMetadata) + +_VALID_CHARS = (frozenset(map(ord, string.ascii_letters)) | + frozenset(map(ord, string.digits)) | + frozenset(map(ord, ' !#$%&\'()*+,-./:;<=>?@[]^_`{|}~'))) + +_SIMPLE_IDENTIFIER_RE = re.compile(r"[-a-zA-Z$._][-a-zA-Z$._0-9]*$") + +_CMP_MAP = { + '>': 'gt', + '<': 'lt', + '==': 'eq', + '!=': 'ne', + '>=': 'ge', + '<=': 'le', +} + + +def _escape_string(text, _map={}): + """ + Escape the given bytestring for safe use as a LLVM array constant. + Any unicode string input is first encoded with utf8 into bytes. + """ + if isinstance(text, str): + text = text.encode() + assert isinstance(text, (bytes, bytearray)) + + if not _map: + for ch in range(256): + if ch in _VALID_CHARS: + _map[ch] = chr(ch) + else: + _map[ch] = '\\%02x' % ch + + buf = [_map[ch] for ch in text] + return ''.join(buf) + + +def _binop(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(lhs, rhs): + if lhs.type != rhs.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (lhs.type, rhs.type)) + + fmt = "{0} ({1} {2}, {3} {4})".format(opname, + lhs.type, lhs.get_reference(), + rhs.type, rhs.get_reference()) + return FormattedConstant(lhs.type, fmt) + + return wrapped + return wrap + + +def _castop(opname): + def wrap(fn): + @functools.wraps(fn) + def wrapped(self, typ): + fn(self, typ) + if typ == self.type: + return self + + op = "{0} ({1} {2} to {3})".format(opname, self.type, + self.get_reference(), typ) + return FormattedConstant(typ, op) + + return wrapped + return wrap + + +class _ConstOpMixin(object): + """ + A mixin defining constant operations, for use in constant-like classes. + """ + + # + # Arithmetic APIs + # + + @_binop('shl') + def shl(self, other): + """ + Left integer shift: + lhs << rhs + """ + + @_binop('lshr') + def lshr(self, other): + """ + Logical (unsigned) right integer shift: + lhs >> rhs + """ + + @_binop('ashr') + def ashr(self, other): + """ + Arithmetic (signed) right integer shift: + lhs >> rhs + """ + + @_binop('add') + def add(self, other): + """ + Integer addition: + lhs + rhs + """ + + @_binop('fadd') + def fadd(self, other): + """ + Floating-point addition: + lhs + rhs + """ + + @_binop('sub') + def sub(self, other): + """ + Integer subtraction: + lhs - rhs + """ + + @_binop('fsub') + def fsub(self, other): + """ + Floating-point subtraction: + lhs - rhs + """ + + @_binop('mul') + def mul(self, other): + """ + Integer multiplication: + lhs * rhs + """ + + @_binop('fmul') + def fmul(self, other): + """ + Floating-point multiplication: + lhs * rhs + """ + + @_binop('udiv') + def udiv(self, other): + """ + Unsigned integer division: + lhs / rhs + """ + + @_binop('sdiv') + def sdiv(self, other): + """ + Signed integer division: + lhs / rhs + """ + + @_binop('fdiv') + def fdiv(self, other): + """ + Floating-point division: + lhs / rhs + """ + + @_binop('urem') + def urem(self, other): + """ + Unsigned integer remainder: + lhs % rhs + """ + + @_binop('srem') + def srem(self, other): + """ + Signed integer remainder: + lhs % rhs + """ + + @_binop('frem') + def frem(self, other): + """ + Floating-point remainder: + lhs % rhs + """ + + @_binop('or') + def or_(self, other): + """ + Bitwise integer OR: + lhs | rhs + """ + + @_binop('and') + def and_(self, other): + """ + Bitwise integer AND: + lhs & rhs + """ + + @_binop('xor') + def xor(self, other): + """ + Bitwise integer XOR: + lhs ^ rhs + """ + + def _cmp(self, prefix, sign, cmpop, other): + ins = prefix + 'cmp' + try: + op = _CMP_MAP[cmpop] + except KeyError: + raise ValueError("invalid comparison %r for %s" % (cmpop, ins)) + + if not (prefix == 'i' and cmpop in ('==', '!=')): + op = sign + op + + if self.type != other.type: + raise ValueError("Operands must be the same type, got (%s, %s)" + % (self.type, other.type)) + + fmt = "{0} {1} ({2} {3}, {4} {5})".format( + ins, op, + self.type, self.get_reference(), + other.type, other.get_reference()) + + return FormattedConstant(types.IntType(1), fmt) + + def icmp_signed(self, cmpop, other): + """ + Signed integer comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._cmp('i', 's', cmpop, other) + + def icmp_unsigned(self, cmpop, other): + """ + Unsigned integer (or pointer) comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=' + """ + return self._cmp('i', 'u', cmpop, other) + + def fcmp_ordered(self, cmpop, other): + """ + Floating-point ordered comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + return self._cmp('f', 'o', cmpop, other) + + def fcmp_unordered(self, cmpop, other): + """ + Floating-point unordered comparison: + lhs rhs + + where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' + """ + return self._cmp('f', 'u', cmpop, other) + + # + # Unary APIs + # + + def not_(self): + """ + Bitwise integer complement: + ~value + """ + if isinstance(self.type, types.VectorType): + rhs = values.Constant(self.type, (-1,) * self.type.count) + else: + rhs = values.Constant(self.type, -1) + + return self.xor(rhs) + + def neg(self): + """ + Integer negative: + -value + """ + zero = values.Constant(self.type, 0) + return zero.sub(self) + + def fneg(self): + """ + Floating-point negative: + -value + """ + fmt = "fneg ({0} {1})".format(self.type, self.get_reference()) + return FormattedConstant(self.type, fmt) + + # + # Cast APIs + # + + @_castop('trunc') + def trunc(self, typ): + """ + Truncating integer downcast to a smaller type. + """ + + @_castop('zext') + def zext(self, typ): + """ + Zero-extending integer upcast to a larger type + """ + + @_castop('sext') + def sext(self, typ): + """ + Sign-extending integer upcast to a larger type. + """ + + @_castop('fptrunc') + def fptrunc(self, typ): + """ + Floating-point downcast to a less precise type. + """ + + @_castop('fpext') + def fpext(self, typ): + """ + Floating-point upcast to a more precise type. + """ + + @_castop('bitcast') + def bitcast(self, typ): + """ + Pointer cast to a different pointer type. + """ + + @_castop('fptoui') + def fptoui(self, typ): + """ + Convert floating-point to unsigned integer. + """ + + @_castop('uitofp') + def uitofp(self, typ): + """ + Convert unsigned integer to floating-point. + """ + + @_castop('fptosi') + def fptosi(self, typ): + """ + Convert floating-point to signed integer. + """ + + @_castop('sitofp') + def sitofp(self, typ): + """ + Convert signed integer to floating-point. + """ + + @_castop('ptrtoint') + def ptrtoint(self, typ): + """ + Cast pointer to integer. + """ + if not isinstance(self.type, types.PointerType): + msg = "can only call ptrtoint() on pointer type, not '%s'" + raise TypeError(msg % (self.type,)) + if not isinstance(typ, types.IntType): + raise TypeError("can only ptrtoint() to integer type, not '%s'" + % (typ,)) + + @_castop('inttoptr') + def inttoptr(self, typ): + """ + Cast integer to pointer. + """ + if not isinstance(self.type, types.IntType): + msg = "can only call inttoptr() on integer constants, not '%s'" + raise TypeError(msg % (self.type,)) + if not isinstance(typ, types.PointerType): + raise TypeError("can only inttoptr() to pointer type, not '%s'" + % (typ,)) + + def gep(self, indices): + """ + Call getelementptr on this pointer constant. + """ + if not isinstance(self.type, types.PointerType): + raise TypeError("can only call gep() on pointer constants, not '%s'" + % (self.type,)) + + outtype = self.type + for i in indices: + outtype = outtype.gep(i) + + strindices = ["{0} {1}".format(idx.type, idx.get_reference()) + for idx in indices] + + op = "getelementptr ({0}, {1} {2}, {3})".format( + self.type.pointee, self.type, + self.get_reference(), ', '.join(strindices)) + return FormattedConstant(outtype.as_pointer(self.addrspace), op) + + +class Value(object): + """ + The base class for all values. + """ + + def __repr__(self): + return "" % (self.__class__.__name__, self.type,) + + +class _Undefined(object): + """ + 'undef': a value for undefined values. + """ + def __new__(cls): + try: + return Undefined + except NameError: + return object.__new__(_Undefined) + + +Undefined = _Undefined() + + +class Constant(_StrCaching, _StringReferenceCaching, _ConstOpMixin, Value): + """ + A constant LLVM value. + """ + + def __init__(self, typ, constant): + assert isinstance(typ, types.Type) + assert not isinstance(typ, types.VoidType) + self.type = typ + constant = typ.wrap_constant_value(constant) + self.constant = constant + + def _to_string(self): + return '{0} {1}'.format(self.type, self.get_reference()) + + def _get_reference(self): + if self.constant is None: + val = self.type.null + + elif self.constant is Undefined: + val = "undef" + + elif isinstance(self.constant, bytearray): + val = 'c"{0}"'.format(_escape_string(self.constant)) + + else: + val = self.type.format_constant(self.constant) + + return val + + @classmethod + def literal_array(cls, elems): + """ + Construct a literal array constant made of the given members. + """ + tys = [el.type for el in elems] + if len(tys) == 0: + raise ValueError("need at least one element") + ty = tys[0] + for other in tys: + if ty != other: + raise TypeError("all elements must have the same type") + return cls(types.ArrayType(ty, len(elems)), elems) + + @classmethod + def literal_struct(cls, elems, packed=False): + """ + Construct a literal structure constant made of the given members. + """ + tys = [el.type for el in elems] + return cls(types.LiteralStructType(tys, packed), elems) + + @property + def addrspace(self): + if not isinstance(self.type, types.PointerType): + raise TypeError("Only pointer constant have address spaces") + return self.type.addrspace + + def __eq__(self, other): + if isinstance(other, Constant): + return str(self) == str(other) + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(str(self)) + + def __repr__(self): + return "" % (self.type, self.constant) + + +class FormattedConstant(Constant): + """ + A constant with an already formatted IR representation. + """ + + def __init__(self, typ, constant): + assert isinstance(constant, str) + Constant.__init__(self, typ, constant) + + def _to_string(self): + return self.constant + + def _get_reference(self): + return self.constant + + +class NamedValue(_StrCaching, _StringReferenceCaching, Value): + """ + The base class for named values. + """ + name_prefix = '%' + deduplicate_name = True + + def __init__(self, parent, type, name): + assert parent is not None + assert isinstance(type, types.Type) + self.parent = parent + self.type = type + self._set_name(name) + + def _to_string(self): + buf = [] + if not isinstance(self.type, types.VoidType): + buf.append("{0} = ".format(self.get_reference())) + self.descr(buf) + return "".join(buf).rstrip() + + def descr(self, buf): + raise NotImplementedError + + def _get_name(self): + return self._name + + def _set_name(self, name): + name = self.parent.scope.register(name, + deduplicate=self.deduplicate_name) + self._name = name + + name = property(_get_name, _set_name) + + def _get_reference(self): + name = self.name + # Quote and escape value name + if '\\' in name or '"' in name: + name = name.replace('\\', '\\5c').replace('"', '\\22') + return '{0}"{1}"'.format(self.name_prefix, name) + + def __repr__(self): + return "" % ( + self.__class__.__name__, self.name, self.type) + + @property + def function_type(self): + ty = self.type + if isinstance(ty, types.PointerType): + ty = self.type.pointee + if isinstance(ty, types.FunctionType): + return ty + else: + raise TypeError("Not a function: {0}".format(self.type)) + + +class MetaDataString(NamedValue): + """ + A metadata string, i.e. a constant string used as a value in a metadata + node. + """ + + def __init__(self, parent, string): + super(MetaDataString, self).__init__(parent, + types.MetaDataType(), + name="") + self.string = string + + def descr(self, buf): + buf += (self.get_reference(), "\n") + + def _get_reference(self): + return '!"{0}"'.format(_escape_string(self.string)) + + _to_string = _get_reference + + def __eq__(self, other): + if isinstance(other, MetaDataString): + return self.string == other.string + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.string) + + +class MetaDataArgument(_StrCaching, _StringReferenceCaching, Value): + """ + An argument value to a function taking metadata arguments. + This can wrap any other kind of LLVM value. + + Do not instantiate directly, Builder.call() will create these + automatically. + """ + + def __init__(self, value): + assert isinstance(value, Value) + assert not isinstance(value.type, types.MetaDataType) + self.type = types.MetaDataType() + self.wrapped_value = value + + def _get_reference(self): + # e.g. "i32* %2" + return "{0} {1}".format(self.wrapped_value.type, + self.wrapped_value.get_reference()) + + _to_string = _get_reference + + +class NamedMetaData(object): + """ + A named metadata node. + + Do not instantiate directly, use Module.add_named_metadata() instead. + """ + + def __init__(self, parent): + self.parent = parent + self.operands = [] + + def add(self, md): + self.operands.append(md) + + +class MDValue(NamedValue): + """ + A metadata node's value, consisting of a sequence of elements ("operands"). + + Do not instantiate directly, use Module.add_metadata() instead. + """ + name_prefix = '!' + + def __init__(self, parent, values, name): + super(MDValue, self).__init__(parent, + types.MetaDataType(), + name=name) + self.operands = tuple(values) + parent.metadata.append(self) + + def descr(self, buf): + operands = [] + for op in self.operands: + if isinstance(op.type, types.MetaDataType): + if isinstance(op, Constant) and op.constant is None: + operands.append("null") + else: + operands.append(op.get_reference()) + else: + operands.append("{0} {1}".format(op.type, op.get_reference())) + operands = ', '.join(operands) + buf += ("!{{ {0} }}".format(operands), "\n") + + def _get_reference(self): + return self.name_prefix + str(self.name) + + def __eq__(self, other): + if isinstance(other, MDValue): + return self.operands == other.operands + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.operands) + + +class DIToken: + """ + A debug information enumeration value that should appear bare in + the emitted metadata. + + Use this to wrap known constants, e.g. the DW_* enumerations. + """ + + def __init__(self, value): + self.value = value + + +class DIValue(NamedValue): + """ + A debug information descriptor, containing key-value pairs. + + Do not instantiate directly, use Module.add_debug_info() instead. + """ + name_prefix = '!' + + def __init__(self, parent, is_distinct, kind, operands, name): + super(DIValue, self).__init__(parent, + types.MetaDataType(), + name=name) + self.is_distinct = is_distinct + self.kind = kind + self.operands = tuple(operands) + parent.metadata.append(self) + + def descr(self, buf): + if self.is_distinct: + buf += ("distinct ",) + operands = [] + for key, value in self.operands: + if value is None: + strvalue = "null" + elif value is True: + strvalue = "true" + elif value is False: + strvalue = "false" + elif isinstance(value, DIToken): + strvalue = value.value + elif isinstance(value, str): + strvalue = '"{}"'.format(_escape_string(value)) + elif isinstance(value, int): + strvalue = str(value) + elif isinstance(value, Constant): + # Support for typed constants (e.g., i32 1, i8 2) + # This calls Constant._to_string() which formats as "type value" + strvalue = str(value) + elif isinstance(value, NamedValue): + strvalue = value.get_reference() + else: + raise TypeError("invalid operand type for debug info: %r" + % (value,)) + operands.append("{0}: {1}".format(key, strvalue)) + operands = ', '.join(operands) + buf += ("!", self.kind, "(", operands, ")\n") + + def _get_reference(self): + return self.name_prefix + str(self.name) + + def __eq__(self, other): + if isinstance(other, DIValue): + return self.is_distinct == other.is_distinct and \ + self.kind == other.kind and \ + self.operands == other.operands + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash((self.is_distinct, self.kind, self.operands)) + + +class GlobalValue(NamedValue, _ConstOpMixin, _HasMetadata): + """ + A global value. + """ + name_prefix = '@' + deduplicate_name = False + + def __init__(self, *args, **kwargs): + super(GlobalValue, self).__init__(*args, **kwargs) + self.linkage = '' + self.storage_class = '' + self.section = '' + self.metadata = {} + + +class GlobalVariable(GlobalValue): + """ + A global variable. + """ + + def __init__(self, module, typ, name, addrspace=0): + assert isinstance(typ, types.Type) + super(GlobalVariable, self).__init__(module, typ.as_pointer(addrspace), + name=name) + self.value_type = typ + self.initializer = None + self.unnamed_addr = False + self.global_constant = False + self.addrspace = addrspace + self.align = None + self.parent.add_global(self) + + def descr(self, buf): + if self.global_constant: + kind = 'constant' + else: + kind = 'global' + + if not self.linkage: + # Default to external linkage + linkage = 'external' if self.initializer is None else '' + else: + linkage = self.linkage + + if linkage: + buf.append(linkage + " ") + if self.storage_class: + buf.append(self.storage_class + " ") + if self.unnamed_addr: + buf.append("unnamed_addr ") + if self.addrspace != 0: + buf.append('addrspace({0:d}) '.format(self.addrspace)) + + buf.append("{kind} {type}" .format(kind=kind, type=self.value_type)) + + if self.initializer is not None: + if self.initializer.type != self.value_type: + raise TypeError("got initializer of type %s " + "for global value type %s" + % (self.initializer.type, self.value_type)) + buf.append(" " + self.initializer.get_reference()) + elif linkage not in ('external', 'extern_weak'): + # emit 'undef' for non-external linkage GV + buf.append(" " + self.value_type(Undefined).get_reference()) + + if self.section: + buf.append(", section \"%s\"" % (self.section,)) + + if self.align is not None: + buf.append(", align %d" % (self.align,)) + + if self.metadata: + buf.append(self._stringify_metadata(leading_comma=True)) + + buf.append("\n") + + +class AttributeSet(set): + """A set of string attribute. + Only accept items listed in *_known*. + + Properties: + * Iterate in sorted order + """ + _known = () + + def __init__(self, args=()): + super().__init__() + if isinstance(args, str): + args = [args] + for name in args: + self.add(name) + + def _expand(self, name, typ): + return name + + def add(self, name): + if name not in self._known: + raise ValueError('unknown attr {!r} for {}'.format(name, self)) + return super(AttributeSet, self).add(name) + + def _to_list(self, typ): + return [self._expand(i, typ) for i in sorted(self)] + + +class FunctionAttributes(AttributeSet): + _known = frozenset([ + 'argmemonly', 'alwaysinline', 'builtin', 'cold', 'convergent', + 'inaccessiblememonly', 'inaccessiblemem_or_argmemonly', 'inlinehint', + 'jumptable', 'minsize', 'naked', 'nobuiltin', 'noduplicate', + 'noimplicitfloat', 'noinline', 'nonlazybind', 'norecurse', + 'noredzone', 'noreturn', 'nounwind', 'optnone', 'optsize', + 'readnone', 'readonly', 'returns_twice', 'sanitize_address', + 'sanitize_memory', 'sanitize_thread', 'ssp', + 'sspreg', 'sspstrong', 'uwtable']) + + def __init__(self, args=()): + self._alignstack = 0 + self._personality = None + super(FunctionAttributes, self).__init__(args) + + def add(self, name): + if ((name == 'alwaysinline' and 'noinline' in self) or + (name == 'noinline' and 'alwaysinline' in self)): + raise ValueError("Can't have alwaysinline and noinline") + + super().add(name) + + @property + def alignstack(self): + return self._alignstack + + @alignstack.setter + def alignstack(self, val): + assert val >= 0 + self._alignstack = val + + @property + def personality(self): + return self._personality + + @personality.setter + def personality(self, val): + assert val is None or isinstance(val, GlobalValue) + self._personality = val + + def _to_list(self, ret_type): + attrs = super()._to_list(ret_type) + if self.alignstack: + attrs.append('alignstack({0:d})'.format(self.alignstack)) + if self.personality: + attrs.append('personality {persty} {persfn}'.format( + persty=self.personality.type, + persfn=self.personality.get_reference())) + return attrs + + +class Function(GlobalValue): + """Represent a LLVM Function but does uses a Module as parent. + Global Values are stored as a set of dependencies (attribute `depends`). + """ + + def __init__(self, module, ftype, name): + assert isinstance(ftype, types.Type) + super(Function, self).__init__(module, ftype.as_pointer(), name=name) + self.ftype = ftype + self.scope = _utils.NameScope() + self.blocks = [] + self.attributes = FunctionAttributes() + self.args = tuple([Argument(self, t) + for t in ftype.args]) + self.return_value = ReturnValue(self, ftype.return_type) + self.parent.add_global(self) + self.calling_convention = '' + + @property + def module(self): + return self.parent + + @property + def entry_basic_block(self): + return self.blocks[0] + + @property + def basic_blocks(self): + return self.blocks + + def append_basic_block(self, name=''): + blk = Block(parent=self, name=name) + self.blocks.append(blk) + return blk + + def insert_basic_block(self, before, name=''): + """Insert block before + """ + blk = Block(parent=self, name=name) + self.blocks.insert(before, blk) + return blk + + def descr_prototype(self, buf): + """ + Describe the prototype ("head") of the function. + """ + state = "define" if self.blocks else "declare" + ret = self.return_value + args = ", ".join(str(a) for a in self.args) + name = self.get_reference() + attrs = ' ' + ' '.join(self.attributes._to_list( + self.ftype.return_type)) if self.attributes else '' + if any(self.args): + vararg = ', ...' if self.ftype.var_arg else '' + else: + vararg = '...' if self.ftype.var_arg else '' + linkage = self.linkage + cconv = self.calling_convention + prefix = " ".join(str(x) for x in [state, linkage, cconv, ret] if x) + metadata = self._stringify_metadata() + metadata = ' {}'.format(metadata) if metadata else '' + section = ' section "{}"'.format(self.section) if self.section else '' + pt_str = "{prefix} {name}({args}{vararg}){attrs}{section}{metadata}\n" + prototype = pt_str.format(prefix=prefix, name=name, args=args, + vararg=vararg, attrs=attrs, section=section, + metadata=metadata) + buf.append(prototype) + + def descr_body(self, buf): + """ + Describe of the body of the function. + """ + for blk in self.blocks: + blk.descr(buf) + + def descr(self, buf): + self.descr_prototype(buf) + if self.blocks: + buf.append("{\n") + self.descr_body(buf) + buf.append("}\n") + + def __str__(self): + buf = [] + self.descr(buf) + return "".join(buf) + + @property + def is_declaration(self): + return len(self.blocks) == 0 + + +class ArgumentAttributes(AttributeSet): + # List from + # https://releases.llvm.org/14.0.0/docs/LangRef.html#parameter-attributes + _known = MappingProxyType({ + # True (emit type), + # False (emit name only) + 'byref': True, + 'byval': True, + 'elementtype': True, + 'immarg': False, + 'inalloca': True, + 'inreg': False, + 'nest': False, + 'noalias': False, + 'nocapture': False, + 'nofree': False, + 'nonnull': False, + 'noundef': False, + 'preallocated': True, + 'returned': False, + 'signext': False, + 'sret': True, + 'swiftasync': False, + 'swifterror': False, + 'swiftself': False, + 'zeroext': False, + }) + + def __init__(self, args=()): + self._align = 0 + self._dereferenceable = 0 + self._dereferenceable_or_null = 0 + super(ArgumentAttributes, self).__init__(args) + + def _expand(self, name, typ): + requires_type = self._known.get(name) + if requires_type: + return f"{name}({typ.pointee})" + else: + return name + + @property + def align(self): + return self._align + + @align.setter + def align(self, val): + assert isinstance(val, int) and val >= 0 + self._align = val + + @property + def dereferenceable(self): + return self._dereferenceable + + @dereferenceable.setter + def dereferenceable(self, val): + assert isinstance(val, int) and val >= 0 + self._dereferenceable = val + + @property + def dereferenceable_or_null(self): + return self._dereferenceable_or_null + + @dereferenceable_or_null.setter + def dereferenceable_or_null(self, val): + assert isinstance(val, int) and val >= 0 + self._dereferenceable_or_null = val + + def _to_list(self, typ): + attrs = super()._to_list(typ) + if self.align: + attrs.append('align {0:d}'.format(self.align)) + if self.dereferenceable: + attrs.append('dereferenceable({0:d})'.format(self.dereferenceable)) + if self.dereferenceable_or_null: + dref = 'dereferenceable_or_null({0:d})' + attrs.append(dref.format(self.dereferenceable_or_null)) + return attrs + + +class _BaseArgument(NamedValue): + def __init__(self, parent, typ, name=''): + assert isinstance(typ, types.Type) + super(_BaseArgument, self).__init__(parent, typ, name=name) + self.parent = parent + self.attributes = ArgumentAttributes() + + def __repr__(self): + return "" % (self.__class__.__name__, self.name, + self.type) + + def add_attribute(self, attr): + self.attributes.add(attr) + + +class Argument(_BaseArgument): + """ + The specification of a function argument. + """ + + def __str__(self): + attrs = self.attributes._to_list(self.type) + if attrs: + return "{0} {1} {2}".format(self.type, ' '.join(attrs), + self.get_reference()) + else: + return "{0} {1}".format(self.type, self.get_reference()) + + +class ReturnValue(_BaseArgument): + """ + The specification of a function's return value. + """ + + def __str__(self): + attrs = self.attributes._to_list(self.type) + if attrs: + return "{0} {1}".format(' '.join(attrs), self.type) + else: + return str(self.type) + + +class Block(NamedValue): + """ + A LLVM IR basic block. A basic block is a sequence of + instructions whose execution always goes from start to end. That + is, a control flow instruction (branch) can only appear as the + last instruction, and incoming branches can only jump to the first + instruction. + """ + + def __init__(self, parent, name=''): + super(Block, self).__init__(parent, types.LabelType(), name=name) + self.scope = parent.scope + self.instructions = [] + self.terminator = None + + @property + def is_terminated(self): + return self.terminator is not None + + @property + def function(self): + return self.parent + + @property + def module(self): + return self.parent.module + + def descr(self, buf): + buf.append("{0}:\n".format(self._format_name())) + buf += [" {0}\n".format(instr) for instr in self.instructions] + + def replace(self, old, new): + """Replace an instruction""" + if old.type != new.type: + raise TypeError("new instruction has a different type") + pos = self.instructions.index(old) + self.instructions.remove(old) + self.instructions.insert(pos, new) + + for bb in self.parent.basic_blocks: + for instr in bb.instructions: + instr.replace_usage(old, new) + + def _format_name(self): + # Per the LLVM Language Ref on identifiers, names matching the following + # regex do not need to be quoted: [%@][-a-zA-Z$._][-a-zA-Z$._0-9]* + # Otherwise, the identifier must be quoted and escaped. + name = self.name + if not _SIMPLE_IDENTIFIER_RE.match(name): + name = name.replace('\\', '\\5c').replace('"', '\\22') + name = '"{0}"'.format(name) + return name + + +class BlockAddress(Value): + """ + The address of a basic block. + """ + + def __init__(self, function, basic_block): + assert isinstance(function, Function) + assert isinstance(basic_block, Block) + self.type = types.IntType(8).as_pointer() + self.function = function + self.basic_block = basic_block + + def __str__(self): + return '{0} {1}'.format(self.type, self.get_reference()) + + def get_reference(self): + return "blockaddress({0}, {1})".format( + self.function.get_reference(), + self.basic_block.get_reference()) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f2b3b082d2722e587263fb4ce5307287715a1d5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__init__.py @@ -0,0 +1,57 @@ +import sys + +import unittest +from unittest import TestCase + +import faulthandler + + +try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() +except BaseException as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) + + +# Try to inject Numba's unittest customizations. +from llvmlite.tests import customize + + +def discover_tests(startdir): + """Discover test under a directory + """ + # Avoid importing unittest + loader = unittest.TestLoader() + suite = loader.discover(startdir) + return suite + + +def run_tests(suite=None, xmloutput=None, verbosity=1): + """ + args + ---- + - suite [TestSuite] + A suite of all tests to run + - xmloutput [str or None] + Path of XML output directory (optional) + - verbosity [int] + Verbosity level of tests output + + Returns the TestResult object after running the test *suite*. + """ + if suite is None: + suite = discover_tests("llvmlite.tests") + if xmloutput is not None: + import xmlrunner + runner = xmlrunner.XMLTestRunner(output=xmloutput) + else: + runner = None + prog = unittest.main(suite=suite, testRunner=runner, exit=False, + verbosity=verbosity) + return prog.result + + +def main(): + res = run_tests() + sys.exit(0 if res.wasSuccessful() else 1) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__main__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..97563d18687da90316eef738c8aa3ffbacec4007 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__main__.py @@ -0,0 +1,3 @@ +from llvmlite.tests import main + +main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f0c4b50d20ffe905b53b3473649c4ff12825d88 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/__main__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71f6c8a4079f0324501c3b2800e5e999056af41b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/__main__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/customize.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/customize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17dca9e931a37b88348660a41381e6b90597fac9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/customize.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/refprune_proto.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/refprune_proto.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f1b42e64c1c2b5e38c72f97bb0d1854d3aca0d0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/refprune_proto.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/test_refprune.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/test_refprune.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb9d48beb30bafe7f42973bc5adff5a27fcf6bf3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/test_refprune.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/test_valuerepr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/test_valuerepr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04a5b549dadfc43965f276aa8ba7f6e1e4055875 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/__pycache__/test_valuerepr.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/customize.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/customize.py new file mode 100644 index 0000000000000000000000000000000000000000..7d747a3ca4343a7cb94911fa1283dbfbc35e0577 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/customize.py @@ -0,0 +1,407 @@ +# XXX Ripped off from numba.tests; we should factor it out somewhere? + +import collections +import contextlib +import cProfile +from io import StringIO +import gc +import os +import multiprocessing +import sys +import time +import unittest +import warnings +from unittest import result, runner, signals + + +# "unittest.main" is really the TestProgram class! +# (defined in a module named itself "unittest.main"...) + +class NumbaTestProgram(unittest.main): + """ + A TestProgram subclass adding the following options: + * a -R option to enable reference leak detection + * a --profile option to enable profiling of the test run + + Currently the options are only added in 3.4+. + """ + + refleak = False + profile = False + multiprocess = False + + def __init__(self, *args, **kwargs): + self.discovered_suite = kwargs.pop('suite', None) + # HACK to force unittest not to change warning display options + # (so that NumbaWarnings don't appear all over the place) + sys.warnoptions.append(':x') + super(NumbaTestProgram, self).__init__(*args, **kwargs) + + def createTests(self): + if self.discovered_suite is not None: + self.test = self.discovered_suite + else: + super(NumbaTestProgram, self).createTests() + + def _getParentArgParser(self): + # NOTE: this hook only exists on Python 3.4+. The options won't be + # added in earlier versions (which use optparse - 3.3 - or getopt() + # - 2.x). + parser = super(NumbaTestProgram, self)._getParentArgParser() + if self.testRunner is None: + parser.add_argument('-R', '--refleak', dest='refleak', + action='store_true', + help='Detect reference / memory leaks') + parser.add_argument('-m', '--multiprocess', dest='multiprocess', + action='store_true', + help='Parallelize tests') + parser.add_argument('--profile', dest='profile', + action='store_true', + help='Profile the test run') + return parser + + def parseArgs(self, argv): + if sys.version_info < (3, 4): + # We want these options to work on all versions, emulate them. + if '-R' in argv: + argv.remove('-R') + self.refleak = True + if '-m' in argv: + argv.remove('-m') + self.multiprocess = True + super(NumbaTestProgram, self).parseArgs(argv) + if self.verbosity <= 0: + # We aren't interested in informational messages / warnings when + # running with '-q'. + self.buffer = True + + def runTests(self): + if self.refleak: + self.testRunner = RefleakTestRunner + + if not hasattr(sys, "gettotalrefcount"): + warnings.warn("detecting reference leaks requires a debug " + "build of Python, only memory leaks will be " + "detected") + + elif self.testRunner is None: + self.testRunner = unittest.TextTestRunner + + if self.multiprocess: + self.testRunner = ParallelTestRunner(self.testRunner, + verbosity=self.verbosity, + failfast=self.failfast, + buffer=self.buffer) + + def run_tests_real(): + super(NumbaTestProgram, self).runTests() + + if self.profile: + filename = os.path.splitext( + os.path.basename(sys.modules['__main__'].__file__) + )[0] + '.prof' + p = cProfile.Profile(timer=time.perf_counter) # 3.3+ + p.enable() + try: + p.runcall(run_tests_real) + finally: + p.disable() + print("Writing test profile data into %r" % (filename,)) + p.dump_stats(filename) + else: + run_tests_real() + + +# Monkey-patch unittest so that individual test modules get our custom +# options for free. +unittest.main = NumbaTestProgram + + +# The reference leak detection code is liberally taken and adapted from +# Python's own Lib/test/regrtest.py. + +def _refleak_cleanup(): + # Collect cyclic trash and read memory statistics immediately after. + try: + func1 = sys.getallocatedblocks + except AttributeError: + def func1(): + return 42 + try: + func2 = sys.gettotalrefcount + except AttributeError: + def func2(): + return 42 + + # Flush standard output, so that buffered data is sent to the OS and + # associated Python objects are reclaimed. + for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__): + if stream is not None: + stream.flush() + + sys._clear_type_cache() + # This also clears the various internal CPython freelists. + gc.collect() + return func1(), func2() + + +class ReferenceLeakError(RuntimeError): + pass + + +class IntPool(collections.defaultdict): + + def __missing__(self, key): + return key + + +class RefleakTestResult(runner.TextTestResult): + + warmup = 3 + repetitions = 6 + + def _huntLeaks(self, test): + self.stream.flush() + + repcount = self.repetitions + nwarmup = self.warmup + rc_deltas = [0] * (repcount - nwarmup) + alloc_deltas = [0] * (repcount - nwarmup) + # Preallocate ints likely to be stored in rc_deltas and alloc_deltas, + # to make sys.getallocatedblocks() less flaky. + _int_pool = IntPool() + for i in range(-200, 200): + _int_pool[i] + + alloc_before = rc_before = 0 + for i in range(repcount): + # Use a pristine, silent result object to avoid recursion + res = result.TestResult() + test.run(res) + # Poorly-written tests may fail when run several times. + # In this case, abort the refleak run and report the failure. + if not res.wasSuccessful(): + self.failures.extend(res.failures) + self.errors.extend(res.errors) + raise AssertionError + del res + alloc_after, rc_after = _refleak_cleanup() + if i >= nwarmup: + rc_deltas[i - nwarmup] = _int_pool[rc_after - rc_before] + alloc_deltas[i - + nwarmup] = _int_pool[alloc_after - + alloc_before] + alloc_before, rc_before = alloc_after, rc_after + return rc_deltas, alloc_deltas + + def addSuccess(self, test): + try: + rc_deltas, alloc_deltas = self._huntLeaks(test) + except AssertionError: + # Test failed when repeated + assert not self.wasSuccessful() + return + + # These checkers return False on success, True on failure + def check_rc_deltas(deltas): + return any(deltas) + + def check_alloc_deltas(deltas): + # At least 1/3rd of 0s + if 3 * deltas.count(0) < len(deltas): + return True + # Nothing else than 1s, 0s and -1s + if not set(deltas) <= set((1, 0, -1)): + return True + return False + + failed = False + + for deltas, item_name, checker in [ + (rc_deltas, 'references', check_rc_deltas), + (alloc_deltas, 'memory blocks', check_alloc_deltas)]: + if checker(deltas): + msg = '%s leaked %s %s, sum=%s' % ( + test, deltas, item_name, sum(deltas)) + failed = True + try: + raise ReferenceLeakError(msg) + except Exception: + exc_info = sys.exc_info() + if self.showAll: + self.stream.write("%s = %r " % (item_name, deltas)) + self.addFailure(test, exc_info) + + if not failed: + super(RefleakTestResult, self).addSuccess(test) + + +class RefleakTestRunner(runner.TextTestRunner): + resultclass = RefleakTestResult + + +def _flatten_suite(test): + """Expand suite into list of tests + """ + if isinstance(test, unittest.TestSuite): + tests = [] + for x in test: + tests.extend(_flatten_suite(x)) + return tests + else: + return [test] + + +class ParallelTestResult(runner.TextTestResult): + """ + A TestResult able to inject results from other results. + """ + + def add_results(self, result): + """ + Add the results from the other *result* to this result. + """ + self.stream.write(result.stream.getvalue()) + self.stream.flush() + self.testsRun += result.testsRun + self.failures.extend(result.failures) + self.errors.extend(result.errors) + self.skipped.extend(result.skipped) + self.expectedFailures.extend(result.expectedFailures) + self.unexpectedSuccesses.extend(result.unexpectedSuccesses) + + +class _MinimalResult(object): + """ + A minimal, picklable TestResult-alike object. + """ + + __slots__ = ( + 'failures', 'errors', 'skipped', 'expectedFailures', + 'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun') + + def fixup_case(self, case): + """ + Remove any unpicklable attributes from TestCase instance *case*. + """ + # Python 3.3 doesn't reset this one. + case._outcomeForDoCleanups = None + + def __init__(self, original_result): + for attr in self.__slots__: + setattr(self, attr, getattr(original_result, attr)) + for case, _ in self.expectedFailures: + self.fixup_case(case) + for case, _ in self.errors: + self.fixup_case(case) + for case, _ in self.failures: + self.fixup_case(case) + + +class _FakeStringIO(object): + """ + A trivial picklable StringIO-alike for Python 2. + """ + + def __init__(self, value): + self._value = value + + def getvalue(self): + return self._value + + +class _MinimalRunner(object): + """ + A minimal picklable object able to instantiate a runner in a + child process and run a test case with it. + """ + + def __init__(self, runner_cls, runner_args): + self.runner_cls = runner_cls + self.runner_args = runner_args + + # Python 2 doesn't know how to pickle instance methods, so we use __call__ + # instead. + + def __call__(self, test): + # Executed in child process + kwargs = self.runner_args + # Force recording of output in a buffer (it will be printed out + # by the parent). + kwargs['stream'] = StringIO() + runner = self.runner_cls(**kwargs) + result = runner._makeResult() + # Avoid child tracebacks when Ctrl-C is pressed. + signals.installHandler() + signals.registerResult(result) + result.failfast = runner.failfast + result.buffer = runner.buffer + with self.cleanup_object(test): + test(result) + # HACK as cStringIO.StringIO isn't picklable in 2.x + result.stream = _FakeStringIO(result.stream.getvalue()) + return _MinimalResult(result) + + @contextlib.contextmanager + def cleanup_object(self, test): + """ + A context manager which cleans up unwanted attributes on a test case + (or any other object). + """ + vanilla_attrs = set(test.__dict__) + try: + yield test + finally: + spurious_attrs = set(test.__dict__) - vanilla_attrs + for name in spurious_attrs: + del test.__dict__[name] + + +class ParallelTestRunner(runner.TextTestRunner): + """ + A test runner which delegates the actual running to a pool of child + processes. + """ + + resultclass = ParallelTestResult + + def __init__(self, runner_cls, **kwargs): + runner.TextTestRunner.__init__(self, **kwargs) + self.runner_cls = runner_cls + self.runner_args = kwargs + + def _run_inner(self, result): + # We hijack TextTestRunner.run()'s inner logic by passing this + # method as if it were a test case. + child_runner = _MinimalRunner(self.runner_cls, self.runner_args) + pool = multiprocessing.Pool() + imap = pool.imap_unordered + try: + for child_result in imap(child_runner, self._test_list): + result.add_results(child_result) + if child_result.shouldStop: + break + return result + finally: + # Kill the still active workers + pool.terminate() + pool.join() + + def run(self, test): + self._test_list = _flatten_suite(test) + # This will call self._run_inner() on the created result object, + # and print out the detailed test results at the end. + return super(ParallelTestRunner, self).run(self._run_inner) + + +try: + import faulthandler +except ImportError: + pass +else: + try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() + except BaseException as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/refprune_proto.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/refprune_proto.py new file mode 100644 index 0000000000000000000000000000000000000000..043a0b67857edb3778781962010233d7eb1c57e6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/refprune_proto.py @@ -0,0 +1,330 @@ +""" +Contains tests and a prototype implementation for the fanout algorithm in +the LLVM refprune pass. +""" + +try: + from graphviz import Digraph +except ImportError: + pass +from collections import defaultdict + +# The entry block. It's always the same. +ENTRY = "A" + + +# The following caseNN() functions returns a 3-tuple of +# (nodes, edges, expected). +# `nodes` maps BB nodes to incref/decref inside the block. +# `edges` maps BB nodes to their successor BB. +# `expected` maps BB-node with incref to a set of BB-nodes with the decrefs, or +# the value can be None, indicating invalid prune. + +def case1(): + edges = { + "A": ["B"], + "B": ["C", "D"], + "C": [], + "D": ["E", "F"], + "E": ["G"], + "F": [], + "G": ["H", "I"], + "I": ["G", "F"], + "H": ["J", "K"], + "J": ["L", "M"], + "K": [], + "L": ["Z"], + "M": ["Z", "O", "P"], + "O": ["Z"], + "P": ["Z"], + "Z": [], + } + nodes = defaultdict(list) + nodes["D"] = ["incref"] + nodes["H"] = ["decref"] + nodes["F"] = ["decref", "decref"] + expected = {"D": {"H", "F"}} + return nodes, edges, expected + + +def case2(): + edges = { + "A": ["B", "C"], + "B": ["C"], + "C": [], + } + nodes = defaultdict(list) + nodes["A"] = ["incref"] + nodes["B"] = ["decref"] + nodes["C"] = ["decref"] + expected = {"A": None} + return nodes, edges, expected + + +def case3(): + nodes, edges, _ = case1() + # adds an invalid edge + edges["H"].append("F") + expected = {"D": None} + return nodes, edges, expected + + +def case4(): + nodes, edges, _ = case1() + # adds an invalid edge + edges["H"].append("E") + expected = {"D": None} + return nodes, edges, expected + + +def case5(): + nodes, edges, _ = case1() + # adds backedge to go before incref + edges["B"].append("I") + expected = {"D": None} + return nodes, edges, expected + + +def case6(): + nodes, edges, _ = case1() + # adds backedge to go before incref + edges["I"].append("B") + expected = {"D": None} + return nodes, edges, expected + + +def case7(): + nodes, edges, _ = case1() + # adds forward jump outside + edges["I"].append("M") + expected = {"D": None} + return nodes, edges, expected + + +def case8(): + edges = { + "entry:": ["A"], + "A": ["B", "C"], + "B": ["C"], + "C": [], + } + nodes = defaultdict(list) + nodes["A"] = ["incref"] + nodes["C"] = ["decref"] + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case9(): + nodes, edges, _ = case8() + # adds back edge + edges["C"].append("B") + expected = {"A": None} + return nodes, edges, expected + + +def case10(): + nodes, edges, _ = case8() + # adds back edge to A + edges["C"].append("A") + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case11(): + nodes, edges, _ = case8() + edges["C"].append("D") + edges["D"] = [] + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case12(): + nodes, edges, _ = case8() + edges["C"].append("D") + edges["D"] = ["A"] + expected = {"A": {"C"}} + return nodes, edges, expected + + +def case13(): + nodes, edges, _ = case8() + edges["C"].append("D") + edges["D"] = ["B"] + expected = {"A": None} + return nodes, edges, expected + + +def make_predecessor_map(edges): + d = defaultdict(set) + for src, outgoings in edges.items(): + for dst in outgoings: + d[dst].add(src) + return d + + +class FanoutAlgorithm: + def __init__(self, nodes, edges, verbose=False): + self.nodes = nodes + self.edges = edges + self.rev_edges = make_predecessor_map(edges) + self.print = print if verbose else self._null_print + + def run(self): + return self.find_fanout_in_function() + + def _null_print(self, *args, **kwargs): + pass + + def find_fanout_in_function(self): + got = {} + for cur_node in self.edges: + for incref in (x for x in self.nodes[cur_node] if x == "incref"): + decref_blocks = self.find_fanout(cur_node) + self.print(">>", cur_node, "===", decref_blocks) + got[cur_node] = decref_blocks + return got + + def find_fanout(self, head_node): + decref_blocks = self.find_decref_candidates(head_node) + self.print("candidates", decref_blocks) + if not decref_blocks: + return None + if not self.verify_non_overlapping( + head_node, decref_blocks, entry=ENTRY + ): + return None + return set(decref_blocks) + + def verify_non_overlapping(self, head_node, decref_blocks, entry): + self.print("verify_non_overlapping".center(80, "-")) + # reverse walk for each decref_blocks + # they should end at head_node + todo = list(decref_blocks) + while todo: + cur_node = todo.pop() + visited = set() + + workstack = [cur_node] + del cur_node + while workstack: + cur_node = workstack.pop() + self.print("cur_node", cur_node, "|", workstack) + if cur_node in visited: + continue # skip + if cur_node == entry: + # Entry node + self.print( + "!! failed because we arrived at entry", cur_node + ) + return False + visited.add(cur_node) + # check all predecessors + self.print( + f" {cur_node} preds {self.get_predecessors(cur_node)}" + ) + for pred in self.get_predecessors(cur_node): + if pred in decref_blocks: + # reject because there's a predecessor in decref_blocks + self.print( + "!! reject because predecessor in decref_blocks" + ) + return False + if pred != head_node: + + workstack.append(pred) + + return True + + def get_successors(self, node): + return tuple(self.edges[node]) + + def get_predecessors(self, node): + return tuple(self.rev_edges[node]) + + def has_decref(self, node): + return "decref" in self.nodes[node] + + def walk_child_for_decref( + self, cur_node, path_stack, decref_blocks, depth=10 + ): + indent = " " * len(path_stack) + self.print(indent, "walk", path_stack, cur_node) + if depth <= 0: + return False # missing + if cur_node in path_stack: + if cur_node == path_stack[0]: + return False # reject interior node backedge + return True # skip + if self.has_decref(cur_node): + decref_blocks.add(cur_node) + self.print(indent, "found decref") + return True + + depth -= 1 + path_stack += (cur_node,) + found = False + for child in self.get_successors(cur_node): + if not self.walk_child_for_decref( + child, path_stack, decref_blocks + ): + found = False + break + else: + found = True + + self.print(indent, f"ret {found}") + return found + + def find_decref_candidates(self, cur_node): + # Forward pass + self.print("find_decref_candidates".center(80, "-")) + path_stack = (cur_node,) + found = False + decref_blocks = set() + for child in self.get_successors(cur_node): + if not self.walk_child_for_decref( + child, path_stack, decref_blocks + ): + found = False + break + else: + found = True + if not found: + return set() + else: + return decref_blocks + + +def check_once(): + nodes, edges, expected = case13() + + # Render graph + G = Digraph() + for node in edges: + G.node(node, shape="rect", label=f"{node}\n" + r"\l".join(nodes[node])) + for node, children in edges.items(): + for child in children: + G.edge(node, child) + + G.view() + + algo = FanoutAlgorithm(nodes, edges, verbose=True) + got = algo.run() + assert expected == got + + +def check_all(): + for k, fn in list(globals().items()): + if k.startswith("case"): + print(f"{fn}".center(80, "-")) + nodes, edges, expected = fn() + algo = FanoutAlgorithm(nodes, edges) + got = algo.run() + assert expected == got + print("ALL PASSED") + + +if __name__ == "__main__": + # check_once() + check_all() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_binding.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_binding.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d777ce7492c2c1ccdac1da51db408ac0215dfc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_binding.py @@ -0,0 +1,3155 @@ +import ctypes +import threading +from ctypes import CFUNCTYPE, c_int, c_int32 +from ctypes.util import find_library +import gc +import locale +import os +import platform +import re +import subprocess +import sys +import unittest +from contextlib import contextmanager +from tempfile import mkstemp + +from llvmlite import ir +from llvmlite import binding as llvm +from llvmlite.binding import ffi +from llvmlite.tests import TestCase + +# arvm7l needs extra ABI symbols to link successfully +if platform.machine() == 'armv7l': + llvm.load_library_permanently('libgcc_s.so.1') + + +is_conda_package = unittest.skipUnless(llvm.package_format == "conda", + ("conda package test only, have " + f"{llvm.package_format}")) +is_wheel_package = unittest.skipUnless(llvm.package_format == "wheel", + ("wheel package test only, have " + f"{llvm.package_format}")) + +_HAVE_LIEF = False +try: + import lief # noqa: F401 + _HAVE_LIEF = True +except ImportError: + pass + + +needs_lief = unittest.skipUnless(_HAVE_LIEF, "test needs py-lief package") + + +def no_de_locale(): + cur = locale.setlocale(locale.LC_ALL) + try: + locale.setlocale(locale.LC_ALL, 'de_DE') + except locale.Error: + return True + else: + return False + finally: + locale.setlocale(locale.LC_ALL, cur) + + +asm_sum = r""" + ; ModuleID = '' + source_filename = "asm_sum.c" + target triple = "{triple}" + %struct.glob_type = type {{ i64, [2 x i64]}} + %struct.glob_type_vec = type {{ i64, <2 x i64>}} + + @glob = global i32 0 + @glob_b = global i8 0 + @glob_f = global float 1.5 + @glob_struct = global %struct.glob_type {{i64 0, [2 x i64] [i64 0, i64 0]}} + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + %.4 = add i32 0, %.3 + ret i32 %.4 + }} + """ + +asm_sum2 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + ret i32 %.3 + }} + """ + +asm_sum3 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i64 @sum(i64 %.1, i64 %.2) {{ + %.3 = add i64 %.1, %.2 + %.4 = add i64 5, %.3 + %.5 = add i64 -5, %.4 + ret i64 %.5 + }} + """ + +asm_sum4 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + ret i32 0 + }} + """ + +asm_mul = r""" + ; ModuleID = '' + target triple = "{triple}" + @mul_glob = global i32 0 + + define i32 @mul(i32 %.1, i32 %.2) {{ + %.3 = mul i32 %.1, %.2 + ret i32 %.3 + }} + """ + +asm_square_sum = r""" + ; ModuleID = '' + target triple = "{triple}" + @mul_glob = global i32 0 + + declare i32 @sum(i32, i32) + define i32 @square_sum(i32 %.1, i32 %.2) {{ + %.3 = call i32 @sum(i32 %.1, i32 %.2) + %.4 = mul i32 %.3, %.3 + ret i32 %.4 + }} + """ + +asm_getversion = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i8* @Py_GetVersion() + + define void @getversion(i32 %.1, i32 %.2) {{ + %1 = call i8* @Py_GetVersion() + ret void + }} + """ + +if platform.python_implementation() == 'PyPy': + asm_getversion = asm_getversion.replace('Py_GetVersion', 'PyPy_GetVersion') + +# `fadd` used on integer inputs +asm_parse_error = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = fadd i32 %.1, %.2 + ret i32 %.3 + }} + """ + +# "%.bug" definition references itself +asm_verification_fail = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @sum() {{ + %.bug = add i32 1, %.bug + ret void + }} + """ + +asm_sum_declare = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i32 @sum(i32 %.1, i32 %.2) + """ + +asm_vararg_declare = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i32 @vararg(i32 %.1, ...) + """ + +asm_double_inaccurate = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + %const = fadd fp128 0xLF3CB1CCF26FBC178452FB4EC7F91DEAD, 0xL00000000000000000000000000000001 + ret void + }} + """ # noqa E501 + +asm_double_locale = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + %const = fadd double 0.0, 3.14 + ret void + }} + """ + + +asm_inlineasm = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + call void asm sideeffect "nop", ""() + ret void + }} + """ + +asm_inlineasm2 = """ + ; ModuleID = '' + target triple = "{triple}" + + define void @inlineme() {{ + ret void + }} + + define i32 @caller(i32 %.1, i32 %.2) {{ + entry: + %stack = alloca i32 + store i32 %.1, i32* %stack + br label %main + main: + %loaded = load i32, i32* %stack + %.3 = add i32 %loaded, %.2 + %.4 = add i32 0, %.3 + call void @inlineme() + ret i32 %.4 + }} +""" + +asm_inlineasm3 = """ +; ModuleID = 'test.c' +source_filename = "test.c" +target triple = "{triple}" + +; Function Attrs: noinline nounwind optnone ssp uwtable +define void @inlineme() noinline !dbg !15 {{ + ret void, !dbg !18 +}} + +; Function Attrs: noinline nounwind optnone ssp uwtable +define i32 @foo(i32 %0, i32 %1) !dbg !19 {{ + %3 = alloca i32, align 4 + %4 = alloca i32, align 4 + store i32 %0, i32* %3, align 4 + call void @llvm.dbg.declare(metadata i32* %3, metadata !23, metadata !DIExpression()), !dbg !24 + store i32 %1, i32* %4, align 4 + call void @llvm.dbg.declare(metadata i32* %4, metadata !25, metadata !DIExpression()), !dbg !26 + call void @inlineme(), !dbg !27 + %5 = load i32, i32* %3, align 4, !dbg !28 + %6 = load i32, i32* %4, align 4, !dbg !29 + %7 = add nsw i32 %5, %6, !dbg !30 + ret i32 %7, !dbg !31 +}} + +; Function Attrs: nofree nosync nounwind readnone speculatable willreturn +declare void @llvm.dbg.declare(metadata, metadata, metadata) #1 + +attributes #1 = {{ nofree nosync nounwind readnone speculatable willreturn }} + +!llvm.module.flags = !{{!1, !2, !3, !4, !5, !6, !7, !8, !9, !10}} +!llvm.dbg.cu = !{{!11}} +!llvm.ident = !{{!14}} + +!0 = !{{i32 2, !"SDK Version", [2 x i32] [i32 12, i32 3]}} +!1 = !{{i32 7, !"Dwarf Version", i32 4}} +!2 = !{{i32 2, !"Debug Info Version", i32 3}} +!3 = !{{i32 1, !"wchar_size", i32 4}} +!4 = !{{i32 1, !"branch-target-enforcement", i32 0}} +!5 = !{{i32 1, !"sign-return-address", i32 0}} +!6 = !{{i32 1, !"sign-return-address-all", i32 0}} +!7 = !{{i32 1, !"sign-return-address-with-bkey", i32 0}} +!8 = !{{i32 7, !"PIC Level", i32 2}} +!9 = !{{i32 7, !"uwtable", i32 1}} +!10 = !{{i32 7, !"frame-pointer", i32 1}} +!11 = distinct !DICompileUnit(language: DW_LANG_C99, file: !12, producer: "Apple clang version 13.1.6 (clang-1316.0.21.2.3)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !13, splitDebugInlining: false, nameTableKind: None, sysroot: "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk", sdk: "MacOSX.sdk") +!12 = !DIFile(filename: "test.c", directory: "/") +!13 = !{{}} +!14 = !{{!"Apple clang version 13.1.6 (clang-1316.0.21.2.3)"}} +!15 = distinct !DISubprogram(name: "inlineme", scope: !12, file: !12, line: 1, type: !16, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13) +!16 = !DISubroutineType(types: !17) +!17 = !{{null}} +!18 = !DILocation(line: 1, column: 22, scope: !15) +!19 = distinct !DISubprogram(name: "foo", scope: !12, file: !12, line: 3, type: !20, scopeLine: 3, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13) +!20 = !DISubroutineType(types: !21) +!21 = !{{!22, !22, !22}} +!22 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) +!23 = !DILocalVariable(name: "a", arg: 1, scope: !19, file: !12, line: 3, type: !22) +!24 = !DILocation(line: 3, column: 13, scope: !19) +!25 = !DILocalVariable(name: "b", arg: 2, scope: !19, file: !12, line: 3, type: !22) +!26 = !DILocation(line: 3, column: 20, scope: !19) +!27 = !DILocation(line: 4, column: 5, scope: !19) +!28 = !DILocation(line: 5, column: 12, scope: !19) +!29 = !DILocation(line: 5, column: 16, scope: !19) +!30 = !DILocation(line: 5, column: 14, scope: !19) +!31 = !DILocation(line: 5, column: 5, scope: !19) +""" # noqa E501 + +licm_asm = r""" +; ModuleID = "" +target triple = "{triple}" + +define double @licm(i32 %0) {{ + %2 = alloca i32, align 4 + %3 = alloca double, align 8 + %4 = alloca i32, align 4 + %5 = alloca double, align 8 + store i32 %0, i32* %2, align 4 + store double 0.000000e+00, double* %3, align 8 + store i32 0, i32* %4, align 4 + br label %6 + +6: ; preds = %14, %1 + %7 = load i32, i32* %4, align 4 + %8 = load i32, i32* %2, align 4 + %9 = icmp slt i32 %7, %8 + br i1 %9, label %10, label %17 + +10: ; preds = %6 + store double 7.000000e+00, double* %5, align 8 + %11 = load double, double* %5, align 8 + %12 = load double, double* %3, align 8 + %13 = fadd double %12, %11 + store double %13, double* %3, align 8 + br label %14 + +14: ; preds = %10 + %15 = load i32, i32* %4, align 4 + %16 = add nsw i32 %15, 1 + store i32 %16, i32* %4, align 4 + br label %6 + +17: ; preds = %6 + %18 = load double, double* %3, align 8 + ret double %18 +}} +""" # noqa E501 + +asm_global_ctors = r""" + ; ModuleID = "" + target triple = "{triple}" + + @A = global i32 undef + + define void @ctor_A() + {{ + store i32 10, i32* @A + ret void + }} + + define void @dtor_A() + {{ + store i32 20, i32* @A + ret void + }} + + define i32 @foo() + {{ + %.2 = load i32, i32* @A + %.3 = add i32 %.2, 2 + ret i32 %.3 + }} + + @llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}] + @llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}] + """ # noqa E501 + +asm_ext_ctors = r""" + ; ModuleID = "" + target triple = "{triple}" + + @A = external global i32 + + define void @ctor_A() + {{ + store i32 10, i32* @A + ret void + }} + + define void @dtor_A() + {{ + store i32 20, i32* @A + ret void + }} + + define i32 @foo() + {{ + %.2 = load i32, i32* @A + %.3 = add i32 %.2, 2 + ret i32 %.3 + }} + + @llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}] + @llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}] + """ # noqa E501 + + +asm_nonalphanum_blocklabel = """; ModuleID = "" +target triple = "unknown-unknown-unknown" +target datalayout = "" + +define i32 @"foo"() +{ +"<>!*''#": + ret i32 12345 +} +""" # noqa W291 # trailing space needed for match later + + +asm_null_constant = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo(i64* %.1) {{ + ret void + }} + + define void @bar() {{ + call void @foo(i64* null) + ret void + }} +""" + + +riscv_asm_ilp32 = [ + 'addi\tsp, sp, -16', + 'sw\ta1, 8(sp)', + 'sw\ta2, 12(sp)', + 'fld\tfa5, 8(sp)', + 'fmv.w.x\tfa4, a0', + 'fcvt.d.s\tfa4, fa4', + 'fadd.d\tfa5, fa4, fa5', + 'fsd\tfa5, 8(sp)', + 'lw\ta0, 8(sp)', + 'lw\ta1, 12(sp)', + 'addi\tsp, sp, 16', + 'ret' +] + + +riscv_asm_ilp32f = [ + 'addi\tsp, sp, -16', + 'sw\ta0, 8(sp)', + 'sw\ta1, 12(sp)', + 'fld\tfa5, 8(sp)', + 'fcvt.d.s\tfa4, fa0', + 'fadd.d\tfa5, fa4, fa5', + 'fsd\tfa5, 8(sp)', + 'lw\ta0, 8(sp)', + 'lw\ta1, 12(sp)', + 'addi\tsp, sp, 16', + 'ret' +] + + +riscv_asm_ilp32d = [ + 'fcvt.d.s\tfa5, fa0', + 'fadd.d\tfa0, fa5, fa1', + 'ret' +] + + +asm_attributes = r""" +declare void @a_readonly_func(i8 *) readonly + +declare i8* @a_arg0_return_func(i8* returned, i32*) +""" + +asm_alloca_optnone = r""" +define double @foo(i32 %i, double %j) optnone noinline { + %I = alloca i32 ; [#uses=4] + %J = alloca double ; [#uses=2] + store i32 %i, i32* %I + store double %j, double* %J + %t1 = load i32, i32* %I ; [#uses=1] + %t2 = add i32 %t1, 1 ; [#uses=1] + store i32 %t2, i32* %I + %t3 = load i32, i32* %I ; [#uses=1] + %t4 = sitofp i32 %t3 to double ; [#uses=1] + %t5 = load double, double* %J ; [#uses=1] + %t6 = fmul double %t4, %t5 ; [#uses=1] + ret double %t6 +} +""" + +asm_declaration = r""" +declare void @test_declare(i32* ) +""" + +# This produces the following output from objdump: +# +# $ objdump -D 632.elf +# +# 632.elf: file format elf64-x86-64 +# +# +# Disassembly of section .text: +# +# 0000000000000000 <__arybo>: +# 0: 48 c1 e2 20 shl $0x20,%rdx +# 4: 48 09 c2 or %rax,%rdx +# 7: 48 89 d0 mov %rdx,%rax +# a: 48 c1 c0 3d rol $0x3d,%rax +# e: 48 31 d0 xor %rdx,%rax +# 11: 48 b9 01 20 00 04 80 movabs $0x7010008004002001,%rcx +# 18: 00 10 70 +# 1b: 48 0f af c8 imul %rax,%rcx + +issue_632_elf = \ + "7f454c4602010100000000000000000001003e00010000000000000000000000000000" \ + "0000000000e0000000000000000000000040000000000040000500010048c1e2204809" \ + "c24889d048c1c03d4831d048b90120000480001070480fafc800000000000000000000" \ + "0000000000000000000000000000002f0000000400f1ff000000000000000000000000" \ + "00000000070000001200020000000000000000001f00000000000000002e7465787400" \ + "5f5f617279626f002e6e6f74652e474e552d737461636b002e737472746162002e7379" \ + "6d746162003c737472696e673e00000000000000000000000000000000000000000000" \ + "0000000000000000000000000000000000000000000000000000000000000000000000" \ + "00000000000000001f0000000300000000000000000000000000000000000000a80000" \ + "0000000000380000000000000000000000000000000100000000000000000000000000" \ + "000001000000010000000600000000000000000000000000000040000000000000001f" \ + "000000000000000000000000000000100000000000000000000000000000000f000000" \ + "01000000000000000000000000000000000000005f0000000000000000000000000000" \ + "0000000000000000000100000000000000000000000000000027000000020000000000" \ + "0000000000000000000000000000600000000000000048000000000000000100000002" \ + "00000008000000000000001800000000000000" + + +issue_632_text = \ + "48c1e2204809c24889d048c1c03d4831d048b90120000480001070480fafc8" + + +asm_tli_exp2 = r""" +; ModuleID = '' +source_filename = "" +target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-pc-windows-msvc" + +declare float @llvm.exp2.f32(float %casted) + +define float @foo(i16 %arg) { +entry: + %casted = sitofp i16 %arg to float + %ret = call float @llvm.exp2.f32(float %casted) + ret float %ret +} +""" # noqa E501 + +asm_phi_blocks = r""" +; ModuleID = '' +target triple = "{triple}" + +define void @foo(i32 %N) {{ + ; unnamed block for testing + %cmp4 = icmp sgt i32 %N, 0 + br i1 %cmp4, label %for.body, label %for.cond.cleanup + +for.cond.cleanup: + ret void + +for.body: + %i.05 = phi i32 [ %inc, %for.body ], [ 0, %0 ] + %inc = add nuw nsw i32 %i.05, 1 + %exitcond.not = icmp eq i32 %inc, %N + br i1 %exitcond.not, label %for.cond.cleanup, label %for.body +}} +""" + +asm_cpp_class = r""" +; Source C++ +;----------------------------------------- +; class MyClass; +; +; class MyClassDefined{ +; MyClass *member; +; MyClass *m2; +; MyClass *m3; +; }; +; +; void foo(MyClass *c, MyClassDefined){ } +;----------------------------------------- +; LLVM-IR by: clang -arch arm64 -S -emit-llvm file.cpp +; ModuleID = 'file.cpp' +source_filename = "class.cpp" +target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128" +target triple = "arm64-apple-macosx13.3.0" + +%class.MyClass = type opaque +%class.MyClassDefined = type { %class.MyClass*, %class.MyClass*, %class.MyClass* } + +; Function Attrs: noinline nounwind optnone ssp uwtable(sync) +define void @_Z3fooP7MyClass14MyClassDefined(%class.MyClass* noundef %0, %class.MyClassDefined* noundef %1) { + %3 = alloca %class.MyClass*, align 8 + store %class.MyClass* %0, %class.MyClass** %3, align 8 + ret void +} + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!llvm.ident = !{!9} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 13, i32 3]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 8, !"branch-target-enforcement", i32 0} +!3 = !{i32 8, !"sign-return-address", i32 0} +!4 = !{i32 8, !"sign-return-address-all", i32 0} +!5 = !{i32 8, !"sign-return-address-with-bkey", i32 0} +!6 = !{i32 7, !"PIC Level", i32 2} +!7 = !{i32 7, !"uwtable", i32 1} +!8 = !{i32 7, !"frame-pointer", i32 1} +!9 = !{!"Apple clang version 14.0.3 (clang-1403.0.22.14.1)"} + +""" # noqa + +asm_cpp_vector = r"""; Source C++ +;----------------------------------------- + +; struct Vector2D{ +; float x, y; +; }; +; +; void foo(Vector2D vec, Vector2D *out) { +; *out = vec; +; } +;----------------------------------------- +; LLVM-IR by: clang -arch x86_64 -S -emit-llvm file.cpp +; ModuleID = 'file.cpp' +source_filename = "class.cpp" +target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-apple-macosx13.3.0" + +%struct.Vector2D = type { float, float } + +; Function Attrs: noinline nounwind optnone ssp uwtable +define void @_Z3foo8Vector2DPS_(<2 x float> %0, %struct.Vector2D* noundef %1) #0 { + %3 = alloca %struct.Vector2D, align 4 + %4 = alloca %struct.Vector2D*, align 8 + %5 = bitcast %struct.Vector2D* %3 to <2 x float>* + store <2 x float> %0, <2 x float>* %5, align 4 + store %struct.Vector2D* %1, %struct.Vector2D** %4, align 8 + %6 = load %struct.Vector2D*, %struct.Vector2D** %4, align 8 + %7 = bitcast %struct.Vector2D* %6 to i8* + %8 = bitcast %struct.Vector2D* %3 to i8* + call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 %7, i8* align 4 %8, i64 8, i1 false) + ret void +} + +; Function Attrs: argmemonly nofree nounwind willreturn +declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture writeonly, i8* noalias nocapture readonly, i64, i1 immarg) #1 + +attributes #0 = { noinline nounwind optnone ssp uwtable "darwin-stkchk-strong-link" "frame-pointer"="all" "min-legal-vector-width"="64" "no-trapping-math"="true" "probe-stack"="___chkstk_darwin" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "tune-cpu"="generic" } +attributes #1 = { argmemonly nofree nounwind willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4} +!llvm.ident = !{!5} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 13, i32 3]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"PIC Level", i32 2} +!3 = !{i32 7, !"uwtable", i32 2} +!4 = !{i32 7, !"frame-pointer", i32 2} +!5 = !{!"Apple clang version 14.0.3 (clang-1403.0.22.14.1)"} + +""" # noqa + + +class BaseTest(TestCase): + + def setUp(self): + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + gc.collect() + self.old_garbage = gc.garbage[:] + gc.garbage[:] = [] + + def tearDown(self): + # Test that no uncollectable objects were created + # (llvmlite objects have a __del__ so a reference cycle could + # create some). + gc.collect() + self.assertEqual(gc.garbage, []) + # This will probably put any existing garbage in gc.garbage again + del self.old_garbage + + def module(self, asm=asm_sum, context=None): + asm = asm.format(triple=llvm.get_default_triple()) + mod = llvm.parse_assembly(asm, context) + return mod + + def glob(self, name='glob', mod=None): + if mod is None: + mod = self.module() + return mod.get_global_variable(name) + + def target_machine(self, *, jit): + target = llvm.Target.from_default_triple() + return target.create_target_machine(jit=jit) + + +class TestDependencies(BaseTest): + """ + Test DLL dependencies are within a certain expected set. + """ + + @unittest.skipUnless(sys.platform.startswith('linux'), + "Linux-specific test") + @unittest.skipUnless(os.environ.get('LLVMLITE_DIST_TEST'), + "Distribution-specific test") + def test_linux(self): + lib_path = ffi.lib._name + env = os.environ.copy() + env['LANG'] = 'C' + p = subprocess.Popen(["objdump", "-p", lib_path], + stdout=subprocess.PIPE, env=env) + out, _ = p.communicate() + self.assertEqual(0, p.returncode) + # Parse library dependencies + lib_pat = re.compile(r'^([+-_a-zA-Z0-9]+)\.so(?:\.\d+){0,3}$') + deps = set() + for line in out.decode().splitlines(): + parts = line.split() + if parts and parts[0] == 'NEEDED': + dep = parts[1] + m = lib_pat.match(dep) + if len(parts) != 2 or not m: + self.fail("invalid NEEDED line: %r" % (line,)) + deps.add(m.group(1)) + # Sanity check that our dependencies were parsed ok + if 'libc' not in deps or 'libpthread' not in deps: + self.fail("failed parsing dependencies? got %r" % (deps,)) + # Ensure all dependencies are expected + allowed = set(['librt', 'libdl', 'libpthread', 'libz', 'libm', + 'libgcc_s', 'libc', 'ld-linux', 'ld64', 'libzstd', + 'libstdc++']) + if platform.python_implementation() == 'PyPy': + allowed.add('libtinfo') + + fails = [] + for dep in deps: + if not dep.startswith('ld-linux-') and dep not in allowed: + fails.append(dep) + if len(fails) == 1: + self.fail("unexpected dependency %r in %r" % (fails[0], deps)) + elif len(fails) > 1: + self.fail("unexpected dependencies %r in %r" % (fails, deps)) + else: + pass # test passes + + +class TestRISCVABI(BaseTest): + """ + Test calling convention of floating point arguments of RISC-V + using different ABI. + """ + triple = "riscv32-unknown-linux" + + def setUp(self): + super().setUp() + llvm.initialize_all_targets() + llvm.initialize_all_asmprinters() + + def check_riscv_target(self): + try: + llvm.Target.from_triple(self.triple) + except RuntimeError as e: + if "No available targets are compatible with triple" in str(e): + self.skipTest("RISCV target unsupported by linked LLVM.") + else: + raise e + + def riscv_target_machine(self, **kwarg): + lltarget = llvm.Target.from_triple(self.triple) + return lltarget.create_target_machine(**kwarg) + + def fpadd_ll_module(self): + f64 = ir.DoubleType() + f32 = ir.FloatType() + fnty = ir.FunctionType(f64, (f32, f64)) + module = ir.Module() + func = ir.Function(module, fnty, name="fpadd") + block = func.append_basic_block() + builder = ir.IRBuilder(block) + a, b = func.args + arg0 = builder.fpext(a, f64) + result = builder.fadd(arg0, b) + builder.ret(result) + + llmod = llvm.parse_assembly(str(module)) + llmod.verify() + return llmod + + def break_up_asm(self, asm): + asm_list = [] + for line in asm.splitlines(): + s_line = line.strip() + if not (s_line.startswith(".") or s_line.startswith("fpadd") + or s_line == ""): + asm_list.append(s_line) + return asm_list + + def test_rv32d_ilp32(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32) + + def test_rv32d_ilp32f(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32f") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32f) + + def test_rv32d_ilp32d(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32d") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32d) + + +class TestMisc(BaseTest): + """ + Test miscellaneous functions in llvm.binding. + """ + + def test_parse_assembly(self): + self.module(asm_sum) + + def test_parse_assembly_error(self): + with self.assertRaises(RuntimeError) as cm: + self.module(asm_parse_error) + s = str(cm.exception) + self.assertIn("parsing error", s) + self.assertIn("invalid operand type", s) + + def test_nonalphanum_block_name(self): + mod = ir.Module() + ft = ir.FunctionType(ir.IntType(32), []) + fn = ir.Function(mod, ft, "foo") + bd = ir.IRBuilder(fn.append_basic_block(name="<>!*''#")) + bd.ret(ir.Constant(ir.IntType(32), 12345)) + asm = str(mod) + self.assertEqual(asm, asm_nonalphanum_blocklabel) + + def test_global_context(self): + gcontext1 = llvm.context.get_global_context() + gcontext2 = llvm.context.get_global_context() + assert gcontext1 == gcontext2 + + def test_dylib_symbols(self): + llvm.add_symbol("__xyzzy", 1234) + llvm.add_symbol("__xyzzy", 5678) + addr = llvm.address_of_symbol("__xyzzy") + self.assertEqual(addr, 5678) + addr = llvm.address_of_symbol("__foobar") + self.assertIs(addr, None) + + def test_get_default_triple(self): + triple = llvm.get_default_triple() + self.assertIsInstance(triple, str) + self.assertTrue(triple) + + def test_get_process_triple(self): + # Sometimes we get synonyms for PPC + def normalize_ppc(arch): + if arch == 'powerpc64le': + return 'ppc64le' + else: + return arch + + triple = llvm.get_process_triple() + default = llvm.get_default_triple() + self.assertIsInstance(triple, str) + self.assertTrue(triple) + + default_arch = normalize_ppc(default.split('-')[0]) + triple_arch = normalize_ppc(triple.split('-')[0]) + # Arch must be equal + self.assertEqual(default_arch, triple_arch) + + def test_get_host_cpu_features(self): + features = llvm.get_host_cpu_features() + # Check the content of `features` + self.assertIsInstance(features, dict) + self.assertIsInstance(features, llvm.FeatureMap) + for k, v in features.items(): + self.assertIsInstance(k, str) + self.assertTrue(k) # single feature string cannot be empty + self.assertIsInstance(v, bool) + self.assertIsInstance(features.flatten(), str) + + re_term = r"[+\-][a-zA-Z0-9\._-]+" + regex = r"^({0}|{0}(,{0})*)?$".format(re_term) + # quick check for our regex + self.assertIsNotNone(re.match(regex, "")) + self.assertIsNotNone(re.match(regex, "+aa")) + self.assertIsNotNone(re.match(regex, "+a,-bb")) + # check CpuFeature.flatten() + if len(features) == 0: + self.assertEqual(features.flatten(), "") + else: + self.assertIsNotNone(re.match(regex, features.flatten())) + + def test_get_host_cpu_name(self): + cpu = llvm.get_host_cpu_name() + self.assertIsInstance(cpu, str) + self.assertTrue(cpu) + + def test_initfini(self): + code = """if 1: + from llvmlite import binding as llvm + + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + llvm.initialize_all_targets() + llvm.initialize_all_asmprinters() + llvm.shutdown() + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_deprecated_init(self): + regex = r"llvmlite.binding.initialize\(\) is deprecated" + with self.assertRaisesRegex(RuntimeError, expected_regex=regex): + llvm.initialize() + + def test_set_option(self): + # We cannot set an option multiple times (LLVM would exit() the + # process), so run the code in a subprocess. + code = """if 1: + from llvmlite import binding as llvm + + llvm.set_option("progname", "-debug-pass=Disabled") + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_version(self): + major, minor, patch = llvm.llvm_version_info + # one of these can be valid + valid = (20,) + self.assertIn(major, valid) + self.assertIn(patch, range(9)) + + def test_check_jit_execution(self): + llvm.check_jit_execution() + + @unittest.skipIf(no_de_locale(), "Locale not available") + def test_print_double_locale(self): + m = self.module(asm_double_locale) + expect = str(m) + # Change the locale so that comma is used as decimal-point + # to trigger the LLVM bug (llvmlite issue #80) + locale.setlocale(locale.LC_ALL, 'de_DE') + # The LLVM bug is trigged by print the module with double constant + got = str(m) + # Changing the locale should not affect the LLVM IR + self.assertEqual(expect, got) + + def test_no_accidental_warnings(self): + code = "from llvmlite import binding" + flags = "-Werror" + cmdargs = [sys.executable, flags, "-c", code] + subprocess.check_call(cmdargs) + + +class TestModuleRef(BaseTest): + + def test_str(self): + mod = self.module() + s = str(mod).strip() + self.assertTrue(s.startswith('; ModuleID ='), s) + + def test_close(self): + mod = self.module() + str(mod) + mod.close() + with self.assertRaises(ctypes.ArgumentError): + str(mod) + mod.close() + + def test_with(self): + mod = self.module() + str(mod) + with mod: + str(mod) + with self.assertRaises(ctypes.ArgumentError): + str(mod) + with self.assertRaises(RuntimeError): + with mod: + pass + + def test_name(self): + mod = self.module() + mod.name = "foo" + self.assertEqual(mod.name, "foo") + mod.name = "bar" + self.assertEqual(mod.name, "bar") + + def test_source_file(self): + mod = self.module() + self.assertEqual(mod.source_file, "asm_sum.c") + + def test_data_layout(self): + mod = self.module() + s = mod.data_layout + self.assertIsInstance(s, str) + mod.data_layout = s + self.assertEqual(s, mod.data_layout) + + def test_triple(self): + mod = self.module() + s = mod.triple + self.assertEqual(s, llvm.get_default_triple()) + mod.triple = '' + self.assertEqual(mod.triple, '') + + def test_verify(self): + # Verify successful + mod = self.module() + self.assertIs(mod.verify(), None) + # Verify failed + mod = self.module(asm_verification_fail) + with self.assertRaises(RuntimeError) as cm: + mod.verify() + s = str(cm.exception) + self.assertIn("%.bug = add i32 1, %.bug", s) + + def test_get_function(self): + mod = self.module() + fn = mod.get_function("sum") + self.assertIsInstance(fn, llvm.ValueRef) + self.assertEqual(fn.name, "sum") + + with self.assertRaises(NameError): + mod.get_function("foo") + + # Check that fn keeps the module instance alive + del mod + str(fn.module) + + def test_get_struct_type(self): + mod = self.module() + st_ty = mod.get_struct_type("struct.glob_type") + self.assertEqual(st_ty.name, "struct.glob_type") + # also match struct names of form "%struct.glob_type.{some_index}" + self.assertIsNotNone(re.match( + r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }', + str(st_ty))) + + with self.assertRaises(NameError): + mod.get_struct_type("struct.doesnt_exist") + + def test_get_global_variable(self): + mod = self.module() + gv = mod.get_global_variable("glob") + self.assertIsInstance(gv, llvm.ValueRef) + self.assertEqual(gv.name, "glob") + + with self.assertRaises(NameError): + mod.get_global_variable("bar") + + # Check that gv keeps the module instance alive + del mod + str(gv.module) + + def test_global_variables(self): + mod = self.module() + it = mod.global_variables + del mod + globs = sorted(it, key=lambda value: value.name) + self.assertEqual(len(globs), 4) + self.assertEqual([g.name for g in globs], + ["glob", "glob_b", "glob_f", "glob_struct"]) + + def test_functions(self): + mod = self.module() + it = mod.functions + del mod + funcs = list(it) + self.assertEqual(len(funcs), 1) + self.assertEqual(funcs[0].name, "sum") + + def test_structs(self): + mod = self.module() + it = mod.struct_types + del mod + structs = list(it) + self.assertEqual(len(structs), 1) + self.assertIsNotNone(re.match(r'struct\.glob_type(\.[\d]+)?', + structs[0].name)) + self.assertIsNotNone(re.match( + r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }', + str(structs[0]))) + + def test_link_in(self): + dest = self.module() + src = self.module(asm_mul) + dest.link_in(src) + self.assertEqual( + sorted(f.name for f in dest.functions), ["mul", "sum"]) + dest.get_function("mul") + dest.close() + with self.assertRaises(ctypes.ArgumentError): + src.get_function("mul") + + def test_link_in_preserve(self): + dest = self.module() + src2 = self.module(asm_mul) + dest.link_in(src2, preserve=True) + self.assertEqual( + sorted(f.name for f in dest.functions), ["mul", "sum"]) + dest.close() + self.assertEqual(sorted(f.name for f in src2.functions), ["mul"]) + src2.get_function("mul") + + def test_link_in_error(self): + # Raise an error by trying to link two modules with the same global + # definition "sum". + dest = self.module() + src = self.module(asm_sum2) + with self.assertRaises(RuntimeError) as cm: + dest.link_in(src) + self.assertIn("symbol multiply defined", str(cm.exception)) + + def test_as_bitcode(self): + mod = self.module() + bc = mod.as_bitcode() + # Refer to http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00064 # noqa E501 + # and http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00092 # noqa E501 + bitcode_wrapper_magic = b'\xde\xc0\x17\x0b' + bitcode_magic = b'BC' + self.assertTrue(bc.startswith(bitcode_magic) or + bc.startswith(bitcode_wrapper_magic)) + + def test_parse_bitcode_error(self): + with self.assertRaises(RuntimeError) as cm: + llvm.parse_bitcode(b"") + self.assertIn("LLVM bitcode parsing error", str(cm.exception)) + self.assertIn( + "file too small to contain bitcode header", str(cm.exception), + ) + + def test_bitcode_roundtrip(self): + # create a new context to avoid struct renaming + context1 = llvm.create_context() + bc = self.module(context=context1).as_bitcode() + context2 = llvm.create_context() + mod = llvm.parse_bitcode(bc, context2) + self.assertEqual(mod.as_bitcode(), bc) + + mod.get_function("sum") + mod.get_global_variable("glob") + + def test_cloning(self): + m = self.module() + cloned = m.clone() + self.assertIsNot(cloned, m) + self.assertEqual(cloned.as_bitcode(), m.as_bitcode()) + + +class JITTestMixin(object): + """ + Mixin for ExecutionEngine tests. + """ + + def get_sum(self, ee, func_name="sum"): + ee.finalize_object() + cfptr = ee.get_function_address(func_name) + self.assertTrue(cfptr) + return CFUNCTYPE(c_int, c_int, c_int)(cfptr) + + def test_run_code(self): + mod = self.module() + with self.jit(mod) as ee: + cfunc = self.get_sum(ee) + res = cfunc(2, -5) + self.assertEqual(-3, res) + + def test_close(self): + ee = self.jit(self.module()) + ee.close() + ee.close() + with self.assertRaises(ctypes.ArgumentError): + ee.finalize_object() + + def test_with(self): + ee = self.jit(self.module()) + with ee: + pass + with self.assertRaises(RuntimeError): + with ee: + pass + with self.assertRaises(ctypes.ArgumentError): + ee.finalize_object() + + def test_module_lifetime(self): + mod = self.module() + ee = self.jit(mod) + ee.close() + mod.close() + + def test_module_lifetime2(self): + mod = self.module() + ee = self.jit(mod) + mod.close() + ee.close() + + def test_add_module(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + with self.assertRaises(KeyError): + ee.add_module(mod) + self.assertFalse(mod.closed) + ee.close() + self.assertTrue(mod.closed) + + def test_add_module_lifetime(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + mod.close() + ee.close() + + def test_add_module_lifetime2(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + ee.close() + mod.close() + + def test_remove_module(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + ee.remove_module(mod) + with self.assertRaises(KeyError): + ee.remove_module(mod) + self.assertFalse(mod.closed) + ee.close() + self.assertFalse(mod.closed) + + def test_target_data(self): + mod = self.module() + ee = self.jit(mod) + td = ee.target_data + # A singleton is returned + self.assertIs(ee.target_data, td) + str(td) + del mod, ee + str(td) + + def test_target_data_abi_enquiries(self): + mod = self.module() + ee = self.jit(mod) + td = ee.target_data + gv_i32 = mod.get_global_variable("glob") + gv_i8 = mod.get_global_variable("glob_b") + gv_struct = mod.get_global_variable("glob_struct") + # A global is a pointer, it has the ABI size of a pointer + pointer_size = 4 if sys.maxsize < 2 ** 32 else 8 + for g in (gv_i32, gv_i8, gv_struct): + self.assertEqual(td.get_abi_size(g.type), pointer_size) + + self.assertEqual(td.get_abi_size(gv_i32.global_value_type), 4) + self.assertEqual(td.get_abi_alignment(gv_i32.global_value_type), 4) + + self.assertEqual(td.get_abi_size(gv_i8.global_value_type), 1) + self.assertIn(td.get_abi_alignment(gv_i8.global_value_type), (1, 2, 4)) + + self.assertEqual(td.get_abi_size(gv_struct.global_value_type), 24) + self.assertIn(td.get_abi_alignment(gv_struct.global_value_type), (4, 8)) + + def test_object_cache_notify(self): + notifies = [] + + def notify(mod, buf): + notifies.append((mod, buf)) + + mod = self.module() + ee = self.jit(mod) + ee.set_object_cache(notify) + + self.assertEqual(len(notifies), 0) + cfunc = self.get_sum(ee) + cfunc(2, -5) + self.assertEqual(len(notifies), 1) + # The right module object was found + self.assertIs(notifies[0][0], mod) + self.assertIsInstance(notifies[0][1], bytes) + + notifies[:] = [] + mod2 = self.module(asm_mul) + ee.add_module(mod2) + cfunc = self.get_sum(ee, "mul") + self.assertEqual(len(notifies), 1) + # The right module object was found + self.assertIs(notifies[0][0], mod2) + self.assertIsInstance(notifies[0][1], bytes) + + def test_object_cache_getbuffer(self): + notifies = [] + getbuffers = [] + + def notify(mod, buf): + notifies.append((mod, buf)) + + def getbuffer(mod): + getbuffers.append(mod) + + mod = self.module() + ee = self.jit(mod) + ee.set_object_cache(notify, getbuffer) + + # First return None from getbuffer(): the object is compiled normally + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 0) + cfunc = self.get_sum(ee) + self.assertEqual(len(notifies), 1) + self.assertEqual(len(getbuffers), 1) + self.assertIs(getbuffers[0], mod) + sum_buffer = notifies[0][1] + + # Recreate a new EE, and use getbuffer() to return the previously + # compiled object. + + def getbuffer_successful(mod): + getbuffers.append(mod) + return sum_buffer + + notifies[:] = [] + getbuffers[:] = [] + # Use another source module to make sure it is ignored + mod = self.module(asm_mul) + ee = self.jit(mod) + ee.set_object_cache(notify, getbuffer_successful) + + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 0) + cfunc = self.get_sum(ee) + self.assertEqual(cfunc(2, -5), -3) + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 1) + + +class JITWithTMTestMixin(JITTestMixin): + + def test_emit_assembly(self): + """Test TargetMachineRef.emit_assembly()""" + target_machine = self.target_machine(jit=True) + mod = self.module() + ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive + raw_asm = target_machine.emit_assembly(mod) + self.assertIn("sum", raw_asm) + target_machine.set_asm_verbosity(True) + raw_asm_verbose = target_machine.emit_assembly(mod) + self.assertIn("sum", raw_asm) + self.assertNotEqual(raw_asm, raw_asm_verbose) + + def test_emit_object(self): + """Test TargetMachineRef.emit_object()""" + target_machine = self.target_machine(jit=True) + mod = self.module() + ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive + code_object = target_machine.emit_object(mod) + self.assertIsInstance(code_object, bytes) + if sys.platform.startswith('linux'): + # Sanity check + self.assertIn(b"ELF", code_object[:10]) + + +class TestMCJit(BaseTest, JITWithTMTestMixin): + """ + Test JIT engines created with create_mcjit_compiler(). + """ + + def jit(self, mod, target_machine=None): + if target_machine is None: + target_machine = self.target_machine(jit=True) + return llvm.create_mcjit_compiler(mod, target_machine) + + +# There are some memory corruption issues with OrcJIT on AArch64 - see Issue +# #1000. Since OrcJIT is experimental, and we don't test regularly during +# llvmlite development on non-x86 platforms, it seems safest to skip these +# tests on non-x86 platforms. +# After LLVM20 upgrades skip on X86 too as ORCJit complains about missing +# JITDyLib symbol. +# TODO: Investigate this further. +@unittest.skip("OrcJIT support is experimental") +class TestOrcLLJIT(BaseTest): + + def jit(self, asm=asm_sum, func_name="sum", target_machine=None, + add_process=False, func_type=CFUNCTYPE(c_int, c_int, c_int), + suppress_errors=False): + lljit = llvm.create_lljit_compiler(target_machine, + use_jit_link=False, + suppress_errors=suppress_errors) + builder = llvm.JITLibraryBuilder() + if add_process: + builder.add_current_process() + rt = builder\ + .add_ir(asm.format(triple=llvm.get_default_triple()))\ + .export_symbol(func_name)\ + .link(lljit, func_name) + cfptr = rt[func_name] + self.assertTrue(cfptr) + self.assertEqual(func_name, rt.name) + return lljit, rt, func_type(cfptr) + + # From test_dylib_symbols + def test_define_symbol(self): + lljit = llvm.create_lljit_compiler() + rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\ + .export_symbol("__xyzzy").link(lljit, "foo") + self.assertEqual(rt["__xyzzy"], 1234) + + def test_lookup_undefined_symbol_fails(self): + lljit = llvm.create_lljit_compiler() + with self.assertRaisesRegex(RuntimeError, 'No such library'): + lljit.lookup("foo", "__foobar") + rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\ + .export_symbol("__xyzzy").link(lljit, "foo") + self.assertNotEqual(rt["__xyzzy"], 0) + with self.assertRaisesRegex(RuntimeError, + 'Symbols not found.*__foobar'): + lljit.lookup("foo", "__foobar") + + def test_jit_link(self): + if sys.platform == "win32": + with self.assertRaisesRegex(RuntimeError, + 'JITLink .* Windows'): + llvm.create_lljit_compiler(use_jit_link=True) + else: + self.assertIsNotNone(llvm.create_lljit_compiler(use_jit_link=True)) + + def test_run_code(self): + (lljit, rt, cfunc) = self.jit() + with lljit: + res = cfunc(2, -5) + self.assertEqual(-3, res) + + def test_close(self): + (lljit, rt, cfunc) = self.jit() + lljit.close() + lljit.close() + with self.assertRaises(AssertionError): + lljit.lookup("foo", "fn") + + def test_with(self): + (lljit, rt, cfunc) = self.jit() + with lljit: + pass + with self.assertRaises(RuntimeError): + with lljit: + pass + with self.assertRaises(AssertionError): + lljit.lookup("foo", "fn") + + def test_add_ir_module(self): + (lljit, rt_sum, cfunc_sum) = self.jit() + rt_mul = llvm.JITLibraryBuilder() \ + .add_ir(asm_mul.format(triple=llvm.get_default_triple())) \ + .export_symbol("mul") \ + .link(lljit, "mul") + res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["mul"])(2, -5) + self.assertEqual(-10, res) + self.assertNotEqual(lljit.lookup("sum", "sum")["sum"], 0) + self.assertNotEqual(lljit.lookup("mul", "mul")["mul"], 0) + with self.assertRaises(RuntimeError): + lljit.lookup("sum", "mul") + with self.assertRaises(RuntimeError): + lljit.lookup("mul", "sum") + + def test_remove_module(self): + (lljit, rt_sum, _) = self.jit() + del rt_sum + gc.collect() + with self.assertRaises(RuntimeError): + lljit.lookup("sum", "sum") + lljit.close() + + def test_lib_depends(self): + (lljit, rt_sum, cfunc_sum) = self.jit() + rt_mul = llvm.JITLibraryBuilder() \ + .add_ir(asm_square_sum.format(triple=llvm.get_default_triple())) \ + .export_symbol("square_sum") \ + .add_jit_library("sum") \ + .link(lljit, "square_sum") + res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["square_sum"])(2, -5) + self.assertEqual(9, res) + + def test_target_data(self): + (lljit, rt, _) = self.jit() + td = lljit.target_data + # A singleton is returned + self.assertIs(lljit.target_data, td) + str(td) + del lljit + str(td) + + def test_global_ctors_dtors(self): + # test issue #303 + # (https://github.com/numba/llvmlite/issues/303) + shared_value = c_int32(0) + lljit = llvm.create_lljit_compiler() + builder = llvm.JITLibraryBuilder() + rt = builder \ + .add_ir(asm_ext_ctors.format(triple=llvm.get_default_triple())) \ + .import_symbol("A", ctypes.addressof(shared_value)) \ + .export_symbol("foo") \ + .link(lljit, "foo") + foo = rt["foo"] + self.assertTrue(foo) + self.assertEqual(CFUNCTYPE(c_int)(foo)(), 12) + del rt + self.assertNotEqual(shared_value.value, 20) + + def test_lookup_current_process_symbol_fails(self): + # An attempt to lookup a symbol in the current process (Py_GetVersion, + # in this case) should fail with an appropriate error if we have not + # enabled searching the current process for symbols. + msg = 'Failed to materialize symbols:.*getversion' + with self.assertRaisesRegex(RuntimeError, msg): + self.jit(asm_getversion, "getversion", suppress_errors=True) + + def test_lookup_current_process_symbol(self): + self.jit(asm_getversion, "getversion", None, True) + + def test_thread_safe(self): + lljit = llvm.create_lljit_compiler() + llvm_ir = asm_sum.format(triple=llvm.get_default_triple()) + + def compile_many(i): + def do_work(): + tracking = [] + for c in range(50): + tracking.append(llvm.JITLibraryBuilder() + .add_ir(llvm_ir) + .export_symbol("sum") + .link(lljit, f"sum_{i}_{c}")) + + return do_work + + ths = [threading.Thread(target=compile_many(i)) + for i in range(os.cpu_count())] + for th in ths: + th.start() + for th in ths: + th.join() + + def test_add_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + lljit = llvm.create_lljit_compiler(target_machine) + rt = llvm.JITLibraryBuilder()\ + .add_object_img(target_machine.emit_object(mod))\ + .export_symbol("sum")\ + .link(lljit, "sum") + sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"]) + self.assertEqual(sum(2, 3), 5) + + def test_add_object_file_from_filesystem(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + temp_desc, temp_path = mkstemp() + + try: + with os.fdopen(temp_desc, "wb") as f: + f.write(obj_bin) + lljit = llvm.create_lljit_compiler(target_machine) + rt = llvm.JITLibraryBuilder() \ + .add_object_file(temp_path) \ + .export_symbol("sum") \ + .link(lljit, "sum") + sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"]) + self.assertEqual(sum(2, 3), 5) + finally: + os.unlink(temp_path) + + +class TestValueRef(BaseTest): + + def test_str(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(str(glob), "@glob = global i32 0") + + def test_name(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(glob.name, "glob") + glob.name = "foobar" + self.assertEqual(glob.name, "foobar") + + def test_linkage(self): + mod = self.module() + glob = mod.get_global_variable("glob") + linkage = glob.linkage + self.assertIsInstance(glob.linkage, llvm.Linkage) + glob.linkage = linkage + self.assertEqual(glob.linkage, linkage) + for linkage in ("internal", "external"): + glob.linkage = linkage + self.assertIsInstance(glob.linkage, llvm.Linkage) + self.assertEqual(glob.linkage.name, linkage) + + def test_visibility(self): + mod = self.module() + glob = mod.get_global_variable("glob") + visibility = glob.visibility + self.assertIsInstance(glob.visibility, llvm.Visibility) + glob.visibility = visibility + self.assertEqual(glob.visibility, visibility) + for visibility in ("hidden", "protected", "default"): + glob.visibility = visibility + self.assertIsInstance(glob.visibility, llvm.Visibility) + self.assertEqual(glob.visibility.name, visibility) + + def test_storage_class(self): + mod = self.module() + glob = mod.get_global_variable("glob") + storage_class = glob.storage_class + self.assertIsInstance(glob.storage_class, llvm.StorageClass) + glob.storage_class = storage_class + self.assertEqual(glob.storage_class, storage_class) + for storage_class in ("dllimport", "dllexport", "default"): + glob.storage_class = storage_class + self.assertIsInstance(glob.storage_class, llvm.StorageClass) + self.assertEqual(glob.storage_class.name, storage_class) + + def test_add_function_attribute(self): + mod = self.module() + fn = mod.get_function("sum") + fn.add_function_attribute("nocapture") + with self.assertRaises(ValueError) as raises: + fn.add_function_attribute("zext") + self.assertEqual(str(raises.exception), "no such attribute 'zext'") + + def test_module(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertIs(glob.module, mod) + + def test_type(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.type + self.assertIsInstance(tp, llvm.TypeRef) + + def test_type_name(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.type + self.assertEqual(tp.name, "") + st = mod.get_global_variable("glob_struct") + self.assertIsNotNone(re.match(r"struct\.glob_type(\.[\d]+)?", + st.global_value_type.name)) + + def test_type_printing_variable(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.global_value_type + self.assertEqual(str(tp), 'i32') + + def test_type_printing_function(self): + mod = self.module() + fn = mod.get_function("sum") + self.assertEqual(str(fn.global_value_type), "i32 (i32, i32)") + + def test_type_printing_struct(self): + mod = self.module() + st = mod.get_global_variable("glob_struct") + self.assertTrue(st.type.is_pointer) + self.assertIsNotNone(re.match(r'ptr', str(st.type))) + self.assertIsNotNone(re.match( + r"%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }", + str(st.global_value_type))) + + def test_close(self): + glob = self.glob() + glob.close() + glob.close() + + def test_is_declaration(self): + defined = self.module().get_function('sum') + declared = self.module(asm_sum_declare).get_function('sum') + self.assertFalse(defined.is_declaration) + self.assertTrue(declared.is_declaration) + + def test_module_global_variables(self): + mod = self.module(asm_sum) + gvars = list(mod.global_variables) + self.assertEqual(len(gvars), 4) + for v in gvars: + self.assertTrue(v.is_global) + + def test_module_functions(self): + mod = self.module() + funcs = list(mod.functions) + self.assertEqual(len(funcs), 1) + func = funcs[0] + self.assertTrue(func.is_function) + self.assertEqual(func.name, 'sum') + + with self.assertRaises(ValueError): + func.instructions + with self.assertRaises(ValueError): + func.operands + with self.assertRaises(ValueError): + func.opcode + + def test_function_arguments(self): + mod = self.module() + func = mod.get_function('sum') + self.assertTrue(func.is_function) + args = list(func.arguments) + self.assertEqual(len(args), 2) + self.assertTrue(args[0].is_argument) + self.assertTrue(args[1].is_argument) + self.assertEqual(args[0].name, '.1') + self.assertEqual(str(args[0].type), 'i32') + self.assertEqual(args[1].name, '.2') + self.assertEqual(str(args[1].type), 'i32') + + with self.assertRaises(ValueError): + args[0].blocks + with self.assertRaises(ValueError): + args[0].arguments + + def test_function_blocks(self): + func = self.module().get_function('sum') + blocks = list(func.blocks) + self.assertEqual(len(blocks), 1) + block = blocks[0] + self.assertTrue(block.is_block) + + def test_block_instructions(self): + func = self.module().get_function('sum') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(len(insts), 3) + self.assertTrue(insts[0].is_instruction) + self.assertTrue(insts[1].is_instruction) + self.assertTrue(insts[2].is_instruction) + self.assertEqual(insts[0].opcode, 'add') + self.assertEqual(insts[1].opcode, 'add') + self.assertEqual(insts[2].opcode, 'ret') + + def test_instruction_operands(self): + func = self.module().get_function('sum') + add = list(list(func.blocks)[0].instructions)[0] + self.assertEqual(add.opcode, 'add') + operands = list(add.operands) + self.assertEqual(len(operands), 2) + self.assertTrue(operands[0].is_operand) + self.assertTrue(operands[1].is_operand) + self.assertEqual(operands[0].name, '.1') + self.assertEqual(str(operands[0].type), 'i32') + self.assertEqual(operands[1].name, '.2') + self.assertEqual(str(operands[1].type), 'i32') + + def test_function_attributes(self): + ver = llvm.llvm_version_info[0] + readonly_attrs = [b'memory(read)' if ver > 15 else b'readonly'] + mod = self.module(asm_attributes) + for func in mod.functions: + attrs = list(func.attributes) + if func.name == 'a_readonly_func': + self.assertEqual(attrs, readonly_attrs) + elif func.name == 'a_arg0_return_func': + self.assertEqual(attrs, []) + args = list(func.arguments) + self.assertEqual(list(args[0].attributes), [b'returned']) + self.assertEqual(list(args[1].attributes), []) + + def test_value_kind(self): + mod = self.module() + self.assertEqual(mod.get_global_variable('glob').value_kind, + llvm.ValueKind.global_variable) + func = mod.get_function('sum') + self.assertEqual(func.value_kind, llvm.ValueKind.function) + block = list(func.blocks)[0] + self.assertEqual(block.value_kind, llvm.ValueKind.basic_block) + inst = list(block.instructions)[1] + self.assertEqual(inst.value_kind, llvm.ValueKind.instruction) + self.assertEqual(list(inst.operands)[0].value_kind, + llvm.ValueKind.constant_int) + self.assertEqual(list(inst.operands)[1].value_kind, + llvm.ValueKind.instruction) + + iasm_func = self.module(asm_inlineasm).get_function('foo') + iasm_inst = list(list(iasm_func.blocks)[0].instructions)[0] + self.assertEqual(list(iasm_inst.operands)[0].value_kind, + llvm.ValueKind.inline_asm) + + def test_is_constant(self): + mod = self.module() + self.assertTrue(mod.get_global_variable('glob').is_constant) + constant_operands = 0 + for func in mod.functions: + self.assertTrue(func.is_constant) + for block in func.blocks: + self.assertFalse(block.is_constant) + for inst in block.instructions: + self.assertFalse(inst.is_constant) + for op in inst.operands: + if op.is_constant: + constant_operands += 1 + + self.assertEqual(constant_operands, 1) + + def test_constant_int(self): + mod = self.module() + func = mod.get_function('sum') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(insts[1].opcode, 'add') + operands = list(insts[1].operands) + self.assertTrue(operands[0].is_constant) + self.assertFalse(operands[1].is_constant) + self.assertEqual(operands[0].get_constant_value(), 0) + with self.assertRaises(ValueError): + operands[1].get_constant_value() + + mod = self.module(asm_sum3) + func = mod.get_function('sum') + insts = list(list(func.blocks)[0].instructions) + posint64 = list(insts[1].operands)[0] + negint64 = list(insts[2].operands)[0] + self.assertEqual(posint64.get_constant_value(), 5) + self.assertEqual(negint64.get_constant_value(signed_int=True), -5) + + # Convert from unsigned arbitrary-precision integer to signed i64 + as_u64 = negint64.get_constant_value(signed_int=False) + as_i64 = int.from_bytes(as_u64.to_bytes(8, 'little'), 'little', + signed=True) + self.assertEqual(as_i64, -5) + + def test_constant_fp(self): + mod = self.module(asm_double_locale) + func = mod.get_function('foo') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(len(insts), 2) + self.assertEqual(insts[0].opcode, 'fadd') + operands = list(insts[0].operands) + self.assertTrue(operands[0].is_constant) + self.assertAlmostEqual(operands[0].get_constant_value(), 0.0) + self.assertTrue(operands[1].is_constant) + self.assertAlmostEqual(operands[1].get_constant_value(), 3.14) + + mod = self.module(asm_double_inaccurate) + func = mod.get_function('foo') + inst = list(list(func.blocks)[0].instructions)[0] + operands = list(inst.operands) + with self.assertRaises(ValueError): + operands[0].get_constant_value() + self.assertAlmostEqual(operands[1].get_constant_value(round_fp=True), 0) + + def test_constant_as_string(self): + mod = self.module(asm_null_constant) + func = mod.get_function('bar') + inst = list(list(func.blocks)[0].instructions)[0] + arg = list(inst.operands)[0] + self.assertTrue(arg.is_constant) + self.assertEqual(arg.get_constant_value(), 'ptr null') + + def test_incoming_phi_blocks(self): + mod = self.module(asm_phi_blocks) + func = mod.get_function('foo') + blocks = list(func.blocks) + instructions = list(blocks[-1].instructions) + self.assertTrue(instructions[0].is_instruction) + self.assertEqual(instructions[0].opcode, 'phi') + + incoming_blocks = list(instructions[0].incoming_blocks) + self.assertEqual(len(incoming_blocks), 2) + self.assertTrue(incoming_blocks[0].is_block) + self.assertTrue(incoming_blocks[1].is_block) + # Test reference to blocks (named or unnamed) + self.assertEqual(incoming_blocks[0], blocks[-1]) + self.assertEqual(incoming_blocks[1], blocks[0]) + + # Test case that should fail + self.assertNotEqual(instructions[1].opcode, 'phi') + with self.assertRaises(ValueError): + instructions[1].incoming_blocks + + +class TestTypeRef(BaseTest): + + def test_str(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(str(glob.global_value_type), "i32") + glob_struct_type = mod.get_struct_type("struct.glob_type") + self.assertEqual(str(glob_struct_type), + "%struct.glob_type = type { i64, [2 x i64] }") + + elements = list(glob_struct_type.elements) + self.assertEqual(len(elements), 2) + self.assertEqual(str(elements[0]), "i64") + self.assertEqual(str(elements[1]), "[2 x i64]") + + def test_type_kind(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(glob.type.type_kind, llvm.TypeKind.pointer) + self.assertTrue(glob.type.is_pointer) + + glob_struct = mod.get_global_variable("glob_struct") + self.assertEqual(glob_struct.type.type_kind, llvm.TypeKind.pointer) + self.assertTrue(glob_struct.type.is_pointer) + + stype = glob_struct.global_value_type + self.assertEqual(stype.type_kind, llvm.TypeKind.struct) + self.assertTrue(stype.is_struct) + + stype_a, stype_b = stype.elements + self.assertEqual(stype_a.type_kind, llvm.TypeKind.integer) + self.assertEqual(stype_b.type_kind, llvm.TypeKind.array) + self.assertTrue(stype_b.is_array) + + glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec") + _, vector_type = glob_vec_struct_type.elements + self.assertEqual(vector_type.type_kind, llvm.TypeKind.vector) + self.assertTrue(vector_type.is_vector) + + funcptr = mod.get_function("sum").type + self.assertEqual(funcptr.type_kind, llvm.TypeKind.pointer) + functype = mod.get_function("sum").global_value_type + self.assertEqual(functype.type_kind, llvm.TypeKind.function) + + def test_element_count(self): + mod = self.module() + glob_struct_type = mod.get_struct_type("struct.glob_type") + _, array_type = glob_struct_type.elements + self.assertEqual(array_type.element_count, 2) + with self.assertRaises(ValueError): + glob_struct_type.element_count + + def test_type_width(self): + mod = self.module() + glob_struct_type = mod.get_struct_type("struct.glob_type") + glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec") + integer_type, array_type = glob_struct_type.elements + _, vector_type = glob_vec_struct_type.elements + self.assertEqual(integer_type.type_width, 64) + self.assertEqual(vector_type.type_width, 64 * 2) + + # Structs and arrays are not primitive types + self.assertEqual(glob_struct_type.type_width, 0) + self.assertEqual(array_type.type_width, 0) + + def test_vararg_function(self): + # Variadic function + mod = self.module(asm_vararg_declare) + func = mod.get_function('vararg') + decltype = func.global_value_type + self.assertTrue(decltype.is_function_vararg) + + mod = self.module(asm_sum_declare) + func = mod.get_function('sum') + decltype = func.global_value_type + self.assertFalse(decltype.is_function_vararg) + + # test that the function pointer type cannot use is_function_vararg + self.assertTrue(func.type.is_pointer) + with self.assertRaises(ValueError) as raises: + func.type.is_function_vararg + self.assertIn("Type ptr is not a function", str(raises.exception)) + + def test_function_typeref_as_ir(self): + mod = self.module() + + [fn] = list(mod.functions) + # .type gives a pointer type, a problem if it's opaque (llvm15+) + self.assertEqual(fn.type.type_kind, llvm.TypeKind.pointer) + self.assertFalse(fn.type.is_function) + # Use .global_value_type instead + fnty = fn.global_value_type + self.assertEqual(fnty.type_kind, llvm.TypeKind.function) + self.assertTrue(fnty.is_function) + # Run .as_ir() to get llvmlite.ir.FunctionType + tyir = fnty.as_ir(ir.global_context) + self.assertIsInstance(tyir, ir.FunctionType) + self.assertEqual(tyir.args, (ir.IntType(32), ir.IntType(32))) + self.assertEqual(tyir.return_type ,ir.IntType(32)) + + def test_void_typeref_as_ir(self): + # Void type can only be used as return-type of llvmlite.ir.FunctionType. + fnty = ir.FunctionType(ir.VoidType(), ()) + irmod = ir.Module() + fn = ir.Function(irmod, fnty, "foo") + mod = self.module(str(irmod)) + fn = mod.get_function("foo") + gvty = fn.global_value_type + self.assertEqual(fnty.return_type, + gvty.as_ir(ir.global_context).return_type) + + def test_global_typeref_as_ir(self): + from llvmlite.binding.typeref import _TypeKindToIRType + ctx = ir.Context() + + skipped = { + "function", # tested in test_function_typeref_as_ir + "void", # tested in test_void_typeref_as_ir + } + + makers = {} + + def maker_half(): + yield ir.HalfType() + + makers['half'] = maker_half + + def maker_float(): + yield ir.FloatType() + + makers['float'] = maker_float + + def maker_double(): + yield ir.DoubleType() + + makers['double'] = maker_double + + def maker_integer(): + yield ir.IntType(32) + + makers['integer'] = maker_integer + + def maker_pointer(): + yield ir.PointerType(ir.IntType(8)) + # opaque struct ptr + yield ctx.get_identified_type("myclass").as_pointer() + # named struct with defined body + myclass2 = ctx.get_identified_type("myclass2") + myclass2.set_body(ir.IntType(8)) + yield myclass2.as_pointer() + + makers['pointer'] = maker_pointer + + def maker_array(): + yield ir.ArrayType(ir.IntType(8), 123) + + makers['array'] = maker_array + + def maker_vector(): + yield ir.VectorType(ir.FloatType(), 2) + + makers['vector'] = maker_vector + + def maker_struct(): + yield ir.LiteralStructType([ir.FloatType(), ir.IntType(64)]) + yield ir.LiteralStructType([ir.FloatType(), ir.IntType(64)], + packed=True) + + makers['struct'] = maker_struct + + # Ensure that number of supported TypeKind matches number of makers + self.assertEqual({x.name for x in _TypeKindToIRType.keys()}, + set(makers.keys()) | set(skipped)) + + # Test each type-kind + for type_kind, irtype in _TypeKindToIRType.items(): + if type_kind.name in skipped: + continue + for ty in makers[type_kind.name](): + with self.subTest(f"{type_kind!s} -> {ty}"): + irmod = ir.Module(context=ctx) + ir.GlobalVariable(irmod, ty, name='gv') + asm = str(irmod) + mod = llvm.parse_assembly(asm) + gv = mod.get_global_variable("gv") + gvty = gv.global_value_type + got = gvty.as_ir(ir.Context()) # fresh context + self.assertEqual(got, ty) + self.assertIsInstance(got, irtype) + + def _check_typeref_as_ir_for_wrappers(self, asm, target_symbol): + # Get a clang++ defined function from a llvm ir + mod = llvm.parse_assembly(asm) + cppfn = mod.get_function(target_symbol) + cppfntype = cppfn.global_value_type + + # Get the function type into a new context + my_context = ir.Context() # don't populate global context + ty = cppfntype.as_ir(ir_ctx=my_context) + + # Build a wrapper module for the cpp function + wrapper_mod = ir.Module(context=my_context) + # declare the original function + declfn = ir.Function(wrapper_mod, ty, name=cppfn.name) + # populate the wrapper function + wrapfn = ir.Function(wrapper_mod, ty, name="wrapper") + builder = ir.IRBuilder(wrapfn.append_basic_block()) + # just call the original function + builder.call(declfn, wrapfn.args) + builder.ret_void() + # Create a new LLVM module with the wrapper + new_mod = llvm.parse_assembly(str(wrapper_mod)) + self.assertTrue(new_mod.get_function(declfn.name).is_declaration, + msg="declfn must not have a body") + # Merge/link the original module into the new module + new_mod.link_in(mod, preserve=True) + self.assertEqual(len(list(new_mod.functions)), + len(list(mod.functions)) + 1, + msg="the only new function is the wrapper") + self.assertFalse(new_mod.get_function(declfn.name).is_declaration, + msg="declfn must have a body now") + self.assertEqual(new_mod.get_function(declfn.name).global_value_type, + new_mod.get_function(wrapfn.name).global_value_type, + msg="declfn and wrapfn must have the same llvm Type") + + def test_typeref_as_ir_for_wrappers_of_cpp_class(self): + """Exercise extracting C++ defined class types. + Contains both opaque and non-opaque class definitions. + """ + self._check_typeref_as_ir_for_wrappers( + asm_cpp_class, + "_Z3fooP7MyClass14MyClassDefined", + ) + + def test_typeref_as_ir_for_wrappers_of_cpp_vector_struct(self): + """Exercise extracting C++ struct types that are passed as vectors. + + IA64 ABI on x86_64 will put struct with two floats as + a vector of two floats. + """ + self._check_typeref_as_ir_for_wrappers( + asm_cpp_vector, + "_Z3foo8Vector2DPS_", + ) + + +class TestTarget(BaseTest): + + def test_from_triple(self): + f = llvm.Target.from_triple + with self.assertRaises(RuntimeError) as cm: + f("foobar") + self.assertIn("No available targets are compatible with", + str(cm.exception)) + triple = llvm.get_default_triple() + target = f(triple) + self.assertEqual(target.triple, triple) + target.close() + + def test_create_target_machine(self): + target = llvm.Target.from_triple(llvm.get_default_triple()) + # With the default settings + target.create_target_machine('', '', 1, 'default', 'default') + # With the host's CPU + cpu = llvm.get_host_cpu_name() + target.create_target_machine(cpu, '', 1, 'default', 'default') + + def test_name(self): + t = llvm.Target.from_triple(llvm.get_default_triple()) + u = llvm.Target.from_default_triple() + self.assertIsInstance(t.name, str) + self.assertEqual(t.name, u.name) + + def test_description(self): + t = llvm.Target.from_triple(llvm.get_default_triple()) + u = llvm.Target.from_default_triple() + self.assertIsInstance(t.description, str) + self.assertEqual(t.description, u.description) + + def test_str(self): + target = llvm.Target.from_triple(llvm.get_default_triple()) + s = str(target) + self.assertIn(target.name, s) + self.assertIn(target.description, s) + + def test_get_parts_from_triple(self): + # Tests adapted from llvm-14::llvm/unittests/ADT/TripleTest.cpp + cases = [ + ("x86_64-scei-ps4", + llvm.targets.Triple(Arch="x86_64", SubArch='', + Vendor="scei", OS="ps4", + Env="unknown", ObjectFormat="ELF")), + ("x86_64-sie-ps4", + llvm.targets.Triple(Arch="x86_64", SubArch='', + Vendor="scei", OS="ps4", + Env="unknown", ObjectFormat="ELF")), + ("powerpc-dunno-notsure", + llvm.targets.Triple(Arch="powerpc", SubArch='', + Vendor="unknown", OS="unknown", + Env="unknown", ObjectFormat="ELF")), + ("powerpcspe-unknown-freebsd", + llvm.targets.Triple(Arch="powerpc", SubArch='spe', + Vendor="unknown", OS="freebsd", + Env="unknown", ObjectFormat="ELF")), + ("armv6hl-none-linux-gnueabi", + llvm.targets.Triple(Arch="arm", SubArch='v6hl', + Vendor="unknown", OS="linux", + Env="gnueabi", ObjectFormat="ELF")), + ("i686-unknown-linux-gnu", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="unknown", OS="linux", + Env="gnu", ObjectFormat="ELF")), + ("i686-apple-macosx", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="apple", OS="macosx", + Env="unknown", ObjectFormat="MachO")), + ("i686-dunno-win32", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="unknown", OS="windows", + Env="msvc", ObjectFormat="COFF")), + ("s390x-ibm-zos", + llvm.targets.Triple(Arch="s390x", SubArch='', + Vendor="ibm", OS="zos", + Env="unknown", ObjectFormat="GOFF")), + ("wasm64-wasi", + llvm.targets.Triple(Arch="wasm64", SubArch='', + Vendor="unknown", OS="wasi", + Env="unknown", ObjectFormat="Wasm")), + ] + + for case in cases: + triple_str, triple_obj = case + res = llvm.get_triple_parts(triple_str) + + self.assertEqual(res, triple_obj) + + +class TestTargetData(BaseTest): + + def target_data(self): + return llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + + def test_get_abi_size(self): + td = self.target_data() + glob = self.glob() + self.assertEqual(td.get_abi_size(glob.type), 8) + + def test_get_pointee_abi_size(self): + td = self.target_data() + + glob = self.glob() + self.assertEqual(td.get_abi_size(glob.global_value_type), 4) + + glob = self.glob("glob_struct") + self.assertEqual(td.get_abi_size(glob.global_value_type), 24) + + def test_get_struct_element_offset(self): + td = self.target_data() + glob = self.glob("glob_struct") + + with self.assertRaises(ValueError): + td.get_element_offset(glob.type, 0) + + struct_type = glob.global_value_type + self.assertEqual(td.get_element_offset(struct_type, 0), 0) + self.assertEqual(td.get_element_offset(struct_type, 1), 8) + + +class TestTargetMachine(BaseTest): + + def test_target_data_from_tm(self): + tm = self.target_machine(jit=False) + td = tm.target_data + mod = self.module() + gv_i32 = mod.get_global_variable("glob") + # A global is a pointer, it has the ABI size of a pointer + pointer_size = 4 if sys.maxsize < 2 ** 32 else 8 + self.assertEqual(td.get_abi_size(gv_i32.type), pointer_size) + + +class TestDylib(BaseTest): + + def test_bad_library(self): + with self.assertRaises(RuntimeError): + llvm.load_library_permanently("zzzasdkf;jasd;l") + + @unittest.skipUnless(platform.system() in ["Linux"], + "test only works on Linux") + def test_libm(self): + libm = find_library("m") + llvm.load_library_permanently(libm) + + +class TestAnalysis(BaseTest): + def build_ir_module(self): + m = ir.Module() + ft = ir.FunctionType(ir.IntType(32), [ir.IntType(32), ir.IntType(32)]) + fn = ir.Function(m, ft, "foo") + bd = ir.IRBuilder(fn.append_basic_block()) + x, y = fn.args + z = bd.add(x, y) + bd.ret(z) + return m + + def test_get_function_cfg_on_ir(self): + mod = self.build_ir_module() + foo = mod.get_global('foo') + dot_showing_inst = llvm.get_function_cfg(foo) + dot_without_inst = llvm.get_function_cfg(foo, show_inst=False) + inst = "%.5 = add i32 %.1, %.2" + self.assertIn(inst, dot_showing_inst) + self.assertNotIn(inst, dot_without_inst) + + def test_function_cfg_on_llvm_value(self): + defined = self.module().get_function('sum') + dot_showing_inst = llvm.get_function_cfg(defined, show_inst=True) + dot_without_inst = llvm.get_function_cfg(defined, show_inst=False) + # Check "digraph" + prefix = 'digraph' + self.assertIn(prefix, dot_showing_inst) + self.assertIn(prefix, dot_without_inst) + # Check function name + fname = "CFG for 'sum' function" + self.assertIn(fname, dot_showing_inst) + self.assertIn(fname, dot_without_inst) + # Check instruction + inst = "%.3 = add i32 %.1, %.2" + self.assertIn(inst, dot_showing_inst) + self.assertNotIn(inst, dot_without_inst) + + +class TestTypeParsing(BaseTest): + @contextmanager + def check_parsing(self): + mod = ir.Module() + # Yield to caller and provide the module for adding + # new GV. + yield mod + # Caller yield back and continue with testing + asm = str(mod) + llvm.parse_assembly(asm) + + def test_literal_struct(self): + # Natural layout + with self.check_parsing() as mod: + typ = ir.LiteralStructType([ir.IntType(32)]) + gv = ir.GlobalVariable(mod, typ, "foo") + # Also test constant text repr + gv.initializer = ir.Constant(typ, [1]) + + # Packed layout + with self.check_parsing() as mod: + typ = ir.LiteralStructType([ir.IntType(32)], + packed=True) + gv = ir.GlobalVariable(mod, typ, "foo") + # Also test constant text repr + gv.initializer = ir.Constant(typ, [1]) + + # Packed layout created from Constant.literal_struct + with self.check_parsing() as mod: + const = ir.Constant.literal_struct([ir.IntType(32)(1), + ir.IntType(32)(2)], + packed=True) + gv = ir.GlobalVariable(mod, const.type, "foo") + gv.initializer = const + + +class TestGlobalConstructors(TestMCJit): + @unittest.skipIf(platform.system() == "Darwin", + "__cxa_atexit is broken on OSX in MCJIT") + def test_global_ctors_dtors(self): + # test issue #303 + # (https://github.com/numba/llvmlite/issues/303) + mod = self.module(asm_global_ctors) + ee = self.jit(mod) + ee.finalize_object() + + ee.run_static_constructors() + + # global variable should have been initialized + ptr_addr = ee.get_global_value_address("A") + ptr_t = ctypes.POINTER(ctypes.c_int32) + ptr = ctypes.cast(ptr_addr, ptr_t) + self.assertEqual(ptr.contents.value, 10) + + foo_addr = ee.get_function_address("foo") + foo = ctypes.CFUNCTYPE(ctypes.c_int32)(foo_addr) + self.assertEqual(foo(), 12) + + ee.run_static_destructors() + + # destructor should have run + self.assertEqual(ptr.contents.value, 20) + + +class TestGlobalVariables(BaseTest): + def check_global_variable_linkage(self, linkage, has_undef=True): + # This test default initializer on global variables with different + # linkages. Some linkages requires an initializer be present, while + # it is optional for others. This test uses ``parse_assembly()`` + # to verify that we are adding an `undef` automatically if user didn't + # specific one for certain linkages. It is a IR syntax error if the + # initializer is not present for certain linkages e.g. "external". + mod = ir.Module() + typ = ir.IntType(32) + gv = ir.GlobalVariable(mod, typ, "foo") + gv.linkage = linkage + asm = str(mod) + # check if 'undef' is present + if has_undef: + self.assertIn('undef', asm) + else: + self.assertNotIn('undef', asm) + # parse assembly to ensure correctness + self.module(asm) + + def test_internal_linkage(self): + self.check_global_variable_linkage('internal') + + def test_common_linkage(self): + self.check_global_variable_linkage('common') + + def test_external_linkage(self): + self.check_global_variable_linkage('external', has_undef=False) + + def test_available_externally_linkage(self): + self.check_global_variable_linkage('available_externally') + + def test_private_linkage(self): + self.check_global_variable_linkage('private') + + def test_linkonce_linkage(self): + self.check_global_variable_linkage('linkonce') + + def test_weak_linkage(self): + self.check_global_variable_linkage('weak') + + def test_appending_linkage(self): + self.check_global_variable_linkage('appending') + + def test_extern_weak_linkage(self): + self.check_global_variable_linkage('extern_weak', has_undef=False) + + def test_linkonce_odr_linkage(self): + self.check_global_variable_linkage('linkonce_odr') + + def test_weak_odr_linkage(self): + self.check_global_variable_linkage('weak_odr') + + +@unittest.skipUnless(platform.machine().startswith('x86'), "only on x86") +class TestInlineAsm(BaseTest): + def test_inlineasm(self): + llvm.initialize_native_asmparser() + m = self.module(asm=asm_inlineasm) + tm = self.target_machine(jit=False) + asm = tm.emit_assembly(m) + self.assertIn('nop', asm) + + +class TestObjectFile(BaseTest): + + mod_asm = """ + ;ModuleID = + target triple = "{triple}" + + declare i32 @sum(i32 %.1, i32 %.2) + + define i32 @sum_twice(i32 %.1, i32 %.2) {{ + %.3 = call i32 @sum(i32 %.1, i32 %.2) + %.4 = call i32 @sum(i32 %.3, i32 %.3) + ret i32 %.4 + }} + """ + + def test_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + obj = llvm.ObjectFileRef.from_data(obj_bin) + # Check that we have a text section, and that she has a name and data + has_text_and_data = False + last_address = -1 + for s in obj.sections(): + if ( + s.is_text() + and len(s.data()) > 0 + and s.address() is not None + and last_address < s.address() + ): + has_text_and_data = True + last_address = s.address() + break + self.assertTrue(has_text_and_data) + + def test_add_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + obj = llvm.ObjectFileRef.from_data(obj_bin) + + jit = llvm.create_mcjit_compiler(self.module(self.mod_asm), + target_machine) + + jit.add_object_file(obj) + + sum_twice = CFUNCTYPE(c_int, c_int, c_int)( + jit.get_function_address("sum_twice")) + + self.assertEqual(sum_twice(2, 3), 10) + + def test_add_object_file_from_filesystem(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + temp_desc, temp_path = mkstemp() + + try: + try: + f = os.fdopen(temp_desc, "wb") + f.write(obj_bin) + f.flush() + finally: + f.close() + + jit = llvm.create_mcjit_compiler(self.module(self.mod_asm), + target_machine) + + jit.add_object_file(temp_path) + finally: + os.unlink(temp_path) + + sum_twice = CFUNCTYPE(c_int, c_int, c_int)( + jit.get_function_address("sum_twice")) + + self.assertEqual(sum_twice(2, 3), 10) + + def test_get_section_content(self): + # See Issue #632 - section contents were getting truncated at null + # bytes. + elf = bytes.fromhex(issue_632_elf) + obj = llvm.ObjectFileRef.from_data(elf) + for s in obj.sections(): + if s.is_text(): + self.assertEqual(len(s.data()), 31) + self.assertEqual(s.data().hex(), issue_632_text) + + +class TestLLVMLockCallbacks(BaseTest): + def test_lock_callbacks(self): + events = [] + + def acq(): + events.append('acq') + + def rel(): + events.append('rel') + + # register callback + llvm.ffi.register_lock_callback(acq, rel) + + # Check: events are initially empty + self.assertFalse(events) + # Call LLVM functions + llvm.create_new_module_pass_manager() + # Check: there must be at least one acq and one rel + self.assertIn("acq", events) + self.assertIn("rel", events) + + # unregister callback + llvm.ffi.unregister_lock_callback(acq, rel) + + # Check: removing non-existent callbacks will trigger a ValueError + with self.assertRaises(ValueError): + llvm.ffi.unregister_lock_callback(acq, rel) + + +class TestPipelineTuningOptions(BaseTest): + + def pto(self): + return llvm.create_pipeline_tuning_options() + + def test_close(self): + pto = self.pto() + pto.close() + + def test_speed_level(self): + pto = self.pto() + self.assertIsInstance(pto.speed_level, int) + for i in range(4): + pto.speed_level = i + self.assertEqual(pto.speed_level, i) + + def test_size_level(self): + pto = self.pto() + self.assertIsInstance(pto.size_level, int) + for i in range(3): + pto.size_level = i + self.assertEqual(pto.size_level, i) + + def test_inlining_threshold(self): + pto = self.pto() + self.assertIsInstance(pto.inlining_threshold, int) + for i in (25, 80, 350): + pto.inlining_threshold = i + + def test_loop_interleaving(self): + pto = self.pto() + self.assertIsInstance(pto.loop_interleaving, bool) + for b in (True, False): + pto.loop_interleaving = b + self.assertEqual(pto.loop_interleaving, b) + + def test_loop_vectorization(self): + pto = self.pto() + self.assertIsInstance(pto.loop_vectorization, bool) + for b in (True, False): + pto.loop_vectorization = b + self.assertEqual(pto.loop_vectorization, b) + + def test_slp_vectorization(self): + pto = self.pto() + self.assertIsInstance(pto.slp_vectorization, bool) + for b in (True, False): + pto.slp_vectorization = b + self.assertEqual(pto.slp_vectorization, b) + + def test_loop_unrolling(self): + pto = self.pto() + self.assertIsInstance(pto.loop_unrolling, bool) + for b in (True, False): + pto.loop_unrolling = b + self.assertEqual(pto.loop_unrolling, b) + + def test_speed_level_constraints(self): + pto = self.pto() + with self.assertRaises(ValueError): + pto.speed_level = 4 + with self.assertRaises(ValueError): + pto.speed_level = -1 + + def test_size_level_constraints(self): + pto = self.pto() + with self.assertRaises(ValueError): + pto.size_level = 3 + with self.assertRaises(ValueError): + pto.speed_level = -1 + with self.assertRaises(ValueError): + pto.speed_level = 3 + pto.size_level = 2 + + +class NewPassManagerMixin(object): + + def pb(self, speed_level=0, size_level=0): + tm = self.target_machine(jit=False) + pto = llvm.create_pipeline_tuning_options(speed_level, size_level) + pb = llvm.create_pass_builder(tm, pto) + return pb + + +class TestPassBuilder(BaseTest, NewPassManagerMixin): + + def test_close(self): + pb = self.pb() + pb.close() + + def test_pto(self): + tm = self.target_machine(jit=False) + pto = llvm.create_pipeline_tuning_options(3, 0) + pto.inlining_threshold = 2 + pto.loop_interleaving = True + pto.loop_vectorization = True + pto.slp_vectorization = True + pto.loop_unrolling = False + pb = llvm.create_pass_builder(tm, pto) + pb.close() + + def test_get_module_pass_manager(self): + pb = self.pb() + mpm = pb.getModulePassManager() + mpm.run(self.module(), pb) + pb.close() + + def test_get_function_pass_manager(self): + pb = self.pb() + fpm = pb.getFunctionPassManager() + fpm.run(self.module().get_function("sum"), pb) + pb.close() + + def test_time_passes(self): + """Test pass timing reports for O3 and O0 optimization levels""" + def run_with_timing(speed_level): + mod = self.module() + pb = self.pb(speed_level=speed_level, size_level=0) + pb.start_pass_timing() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + report = pb.finish_pass_timing() + pb.close() + return report + + report_O3 = run_with_timing(3) + report_O0 = run_with_timing(0) + + self.assertIsInstance(report_O3, str) + self.assertIsInstance(report_O0, str) + self.assertEqual(report_O3.count("Pass execution timing report"), 1) + self.assertEqual(report_O0.count("Pass execution timing report"), 1) + + def test_empty_report(self): + mod = self.module() + pb = self.pb() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + pb.start_pass_timing() + report = pb.finish_pass_timing() + pb.close() + self.assertFalse(report) + + def test_multiple_timers_error(self): + mod = self.module() + pb = self.pb() + pb.start_pass_timing() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + pb.finish_pass_timing() + with self.assertRaisesRegex(RuntimeError, "only be done once"): + pb.start_pass_timing() + pb.close() + + def test_empty_report_error(self): + mod = self.module() + pb = self.pb() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + with self.assertRaisesRegex(RuntimeError, "not enabled"): + pb.finish_pass_timing() + pb.close() + + +class TestNewModulePassManager(BaseTest, NewPassManagerMixin): + def pm(self): + return llvm.create_new_module_pass_manager() + + def run_o_n(self, level): + mod = self.module() + orig_asm = str(mod) + pb = self.pb(speed_level=level, size_level=0) + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + optimized_asm = str(mod) + return orig_asm, optimized_asm + + def test_close(self): + mpm = self.pm() + mpm.close() + + def test_run_o3(self): + orig_asm, optimized_asm = self.run_o_n(3) + self.assertIn("%.4", orig_asm) + self.assertNotIn("%.4", optimized_asm) + + def test_run_o0(self): + orig_asm, optimized_asm = self.run_o_n(0) + self.assertIn("%.4", orig_asm) + self.assertIn("%.4", optimized_asm) + + def test_instcombine(self): + pb = self.pb() + mpm = self.pm() + mpm.add_instruction_combine_pass() + mod = self.module(asm_sum4) + orig_asm = str(mod) + mpm.run(mod, pb) + optimized_asm = str(mod) + self.assertIn("%.3", orig_asm) + self.assertNotIn("%.3", optimized_asm) + + def test_optnone(self): + pb = self.pb(speed_level=3, size_level=0) + orig_asm = str(asm_alloca_optnone.replace("optnone ", "")) + mod = llvm.parse_assembly(orig_asm) + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + optimized_asm = str(mod) + self.assertIn("alloca", orig_asm) + self.assertNotIn("alloca", optimized_asm) + + # Module shouldn't be optimized if the function has `optnone` attached + orig_asm_optnone = str(asm_alloca_optnone) + mpm = pb.getModulePassManager() + mod = llvm.parse_assembly(orig_asm_optnone) + mpm.run(mod, pb) + optimized_asm_optnone = str(mod) + self.assertIn("alloca", orig_asm_optnone) + self.assertIn("alloca", optimized_asm_optnone) + + def test_add_passes(self): + mpm = self.pm() + mpm.add_argument_promotion_pass() + mpm.add_post_order_function_attributes_pass() + mpm.add_verifier() + mpm.add_constant_merge_pass() + mpm.add_dead_arg_elimination_pass() + mpm.add_dot_call_graph_printer_pass() + mpm.add_always_inliner_pass() + mpm.add_rpo_function_attrs_pass() + mpm.add_global_dead_code_eliminate_pass() + mpm.add_global_opt_pass() + mpm.add_ipsccp_pass() + mpm.add_internalize_pass() + mpm.add_loop_extract_pass() + mpm.add_merge_functions_pass() + mpm.add_partial_inliner_pass() + mpm.add_strip_symbols_pass() + mpm.add_strip_dead_debug_info_pass() + mpm.add_strip_dead_prototype_pass() + mpm.add_strip_debug_declare_pass() + mpm.add_strip_non_debug_symbols_pass() + mpm.add_aa_eval_pass() + mpm.add_simplify_cfg_pass() + mpm.add_loop_unroll_pass() + mpm.add_instruction_combine_pass() + mpm.add_jump_threading_pass() + mpm.add_cfg_printer_pass() + mpm.add_cfg_only_printer_pass() + mpm.add_dom_printer_pass() + mpm.add_dom_only_printer_pass() + mpm.add_post_dom_printer_pass() + mpm.add_post_dom_only_printer_pass() + mpm.add_dom_viewer_pass() + mpm.add_dom_only_printer_pass() + mpm.add_post_dom_viewer_pass() + mpm.add_post_dom_only_viewer_pass() + mpm.add_lint_pass() + mpm.add_aggressive_dce_pass() + mpm.add_break_critical_edges_pass() + mpm.add_dead_store_elimination_pass() + mpm.add_dead_code_elimination_pass() + mpm.add_aggressive_instcombine_pass() + mpm.add_lcssa_pass() + mpm.add_new_gvn_pass() + mpm.add_loop_simplify_pass() + mpm.add_loop_unroll_and_jam_pass() + mpm.add_sccp_pass() + mpm.add_lower_atomic_pass() + mpm.add_lower_invoke_pass() + mpm.add_lower_switch_pass() + mpm.add_mem_copy_opt_pass() + mpm.add_unify_function_exit_nodes_pass() + mpm.add_reassociate_pass() + mpm.add_register_to_memory_pass() + mpm.add_sroa_pass() + mpm.add_sinking_pass() + mpm.add_tail_call_elimination_pass() + mpm.add_instruction_namer_pass() + mpm.add_loop_deletion_pass() + mpm.add_loop_strength_reduce_pass() + mpm.add_loop_rotate_pass() + mpm.add_refprune_pass() + + +class TestNewFunctionPassManager(BaseTest, NewPassManagerMixin): + def pm(self): + return llvm.create_new_function_pass_manager() + + def test_close(self): + fpm = self.pm() + fpm.close() + + def run_o_n(self, level): + mod = self.module() + fun = mod.get_function("sum") + orig_asm = str(fun) + pb = self.pb(speed_level=level, size_level=0) + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm = str(fun) + return orig_asm, optimized_asm + + def test_run_o3(self): + orig_asm, optimized_asm = self.run_o_n(3) + self.assertIn("%.4", orig_asm) + self.assertNotIn("%.4", optimized_asm) + + def test_run_o0(self): + orig_asm, optimized_asm = self.run_o_n(0) + self.assertIn("%.4", orig_asm) + self.assertIn("%.4", optimized_asm) + + def test_optnone(self): + pb = self.pb(speed_level=3, size_level=0) + orig_asm = str(asm_alloca_optnone.replace("optnone ", "")) + fun = llvm.parse_assembly(orig_asm).get_function("foo") + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm = str(fun) + self.assertIn("alloca", orig_asm) + self.assertNotIn("alloca", optimized_asm) + + # Function shouldn't be optimized if the function has `optnone` attached + orig_asm_optnone = str(asm_alloca_optnone) + fun = llvm.parse_assembly(orig_asm_optnone).get_function("foo") + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm_optnone = str(fun) + self.assertIn("alloca", orig_asm_optnone) + self.assertIn("alloca", optimized_asm_optnone) + + def test_instcombine(self): + pb = self.pb() + fpm = self.pm() + fun = self.module(asm_sum4).get_function("sum") + fpm.add_instruction_combine_pass() + orig_asm = str(fun) + fpm.run(fun, pb) + optimized_asm = str(fun) + self.assertIn("%.3", orig_asm) + self.assertNotIn("%.3", optimized_asm) + + # This should not crash + def test_declarations(self): + pb = self.pb(3) + fpm = pb.getFunctionPassManager() + for fun in llvm.parse_assembly(asm_declaration).functions: + fpm.run(fun, pb) + + def test_add_passes(self): + fpm = self.pm() + fpm.add_aa_eval_pass() + fpm.add_simplify_cfg_pass() + fpm.add_loop_unroll_pass() + fpm.add_instruction_combine_pass() + fpm.add_jump_threading_pass() + fpm.add_cfg_printer_pass() + fpm.add_cfg_only_printer_pass() + fpm.add_dom_printer_pass() + fpm.add_dom_only_printer_pass() + fpm.add_post_dom_printer_pass() + fpm.add_post_dom_only_printer_pass() + fpm.add_dom_viewer_pass() + fpm.add_dom_only_printer_pass() + fpm.add_post_dom_viewer_pass() + fpm.add_post_dom_only_viewer_pass() + fpm.add_lint_pass() + fpm.add_aggressive_dce_pass() + fpm.add_break_critical_edges_pass() + fpm.add_dead_store_elimination_pass() + fpm.add_dead_code_elimination_pass() + fpm.add_aggressive_instcombine_pass() + fpm.add_lcssa_pass() + fpm.add_new_gvn_pass() + fpm.add_loop_simplify_pass() + fpm.add_loop_unroll_and_jam_pass() + fpm.add_sccp_pass() + fpm.add_lower_atomic_pass() + fpm.add_lower_invoke_pass() + fpm.add_lower_switch_pass() + fpm.add_mem_copy_opt_pass() + fpm.add_unify_function_exit_nodes_pass() + fpm.add_reassociate_pass() + fpm.add_register_to_memory_pass() + fpm.add_sroa_pass() + fpm.add_sinking_pass() + fpm.add_tail_call_elimination_pass() + fpm.add_instruction_namer_pass() + fpm.add_loop_deletion_pass() + fpm.add_loop_strength_reduce_pass() + fpm.add_loop_rotate_pass() + fpm.add_refprune_pass() + + +@unittest.skipUnless(os.environ.get('LLVMLITE_DIST_TEST'), + "Distribution-specific test") +@needs_lief +class TestBuild(TestCase): + # These tests are for use by the Numba project maintainers to check that + # package builds for which they are responsible are producing artifacts in + # the expected way. If you are a package maintainer and these tests are + # running, they shouldn't be by default. The only way they will run is if + # the environment variable LLVMLITE_DIST_TEST is set. The things they are + # checking are based on how the Numba project maintainers want to ship the + # packages, this may be entirely different to how other maintainers wish to + # ship. Basically, don't enable these tests unless you are sure they are + # suitable for your use case. + # + # The llvmlite DSO is the foundation of Numba's JIT compiler stack and is + # also used by other similar projects. It has to link against LLVM as that + # is what provides the tooling to do e.g. IR generation and JIT compilation. + # There are various options surrounding how to build LLVM and then how to + # link it into llvmlite. There have been many occurences of surprising + # linkages, symbol collisions and various other issues. + # + # The following tests are designed to try and test out some of the more + # common combinations of package type and linkage. + # + # NOTE: For Numba project maintainers on packaging formats and expected + # linkage. The following dictionaries capture the state of linkage as of + # llvmlite release 0.44. This is not an indication that it is correct, just + # that this is what is present in practice and clearly "works" to a large + # degree by virtue of having fixed the few reported issues. If you need to + # modify these dictionaries based on new information, that's fine, just make + # sure that it is an understood action opposed to just capturing what + # happened! + + wheel_expected = {"linux": {"x86_64": set(["pthread", + "z", + "dl", + "m", + "gcc_s", + "c", + "rt", + "stdc++", + "ld-linux-x86-64",]), + "aarch64": set(["pthread", + "z", + "dl", + "m", + "gcc_s", + "c", + "rt", + "stdc++",]), + }, # end linux + # NOTE: on windows, this includes a "capture what is + # present and known to work and make sure it doesn"t + # change" approach. + "windows": {"amd64": set(["advapi32", + "kernel32", + "ntdll", + "msvcp140", + "vcruntime140", + "vcruntime140_1", + "api-ms-win-crt-convert-l1-1-0", + "api-ms-win-crt-environment-l1-1-0", # noqa: E501 + "api-ms-win-crt-heap-l1-1-0", + "api-ms-win-crt-locale-l1-1-0", + "api-ms-win-crt-math-l1-1-0", + "api-ms-win-crt-runtime-l1-1-0", + "api-ms-win-crt-stdio-l1-1-0", + "api-ms-win-crt-string-l1-1-0", + "api-ms-win-crt-time-l1-1-0", + "api-ms-win-crt-utility-l1-1-0", + "shell32", # this is delayed + "ole32",]), # also delayed + }, # end windows + "darwin": {"x86_64": set(["llvmlite", + "system", + "z", + "corefoundation", + "c++",]), + "arm64": set(["llvmlite", + "system", + "z", + "c++",]), + },# end darwin + } # end wheel_expected + + conda_expected = {"linux": {"x86_64": set(["pthread", + "z", + "zstd", + "dl", + "m", + "gcc_s", + "c", + # "stdc++", conda has static c++ + "ld-linux-x86-64",]), + "aarch64": set(["pthread", + "z", + "zstd", + "dl", + "m", + "gcc_s", + "c", + # "stdc++", conda has static c++ # noqa: E501 + "ld-linux-aarch64",]), + }, # end linux + # NOTE: on windows, this includes a "capture what is + # present and known to work and make sure it doesn"t + # change" approach. + "windows": {"amd64": set(["z", + "zstd", + "advapi32", + "kernel32", + "ntdll", + "msvcp140", + "vcruntime140", + "vcruntime140_1", + "api-ms-win-crt-convert-l1-1-0", + "api-ms-win-crt-environment-l1-1-0", # noqa: E501 + "api-ms-win-crt-heap-l1-1-0", + "api-ms-win-crt-locale-l1-1-0", + "api-ms-win-crt-math-l1-1-0", + "api-ms-win-crt-runtime-l1-1-0", + "api-ms-win-crt-stdio-l1-1-0", + "api-ms-win-crt-string-l1-1-0", + "api-ms-win-crt-time-l1-1-0", + "api-ms-win-crt-utility-l1-1-0", + "shell32", # this is delayed + "ole32",]), # also delayed + }, # end windows + "darwin": {"x86_64": set(["llvmlite", + "system", + "z", + "zstd", + "corefoundation", + "c++",]), + "arm64": set(["llvmlite", + "system", + "z", + "zstd", + "c++",]), + },# end darwin + } # end wheel_expected + + def check_linkage(self, info, package_type): + machine = platform.machine().lower() + os_name = platform.system().lower() + + if package_type == "wheel": + expected = self.wheel_expected[os_name][machine] + elif package_type == "conda": + expected = self.conda_expected[os_name][machine] + else: + raise ValueError(f"Unexpected package type: {package_type}") + + got = set(info["canonicalised_linked_libraries"]) + # Normalize delvewheel-bundled MSVCP hashed name (e.g. msvcp140-) + got = { + ("msvcp140" if lib.startswith("msvcp140") else lib) + for lib in got + } + + try: + self.assertEqual(expected, got) + except AssertionError as e: + msg = ("Unexpected linkage encountered for libllvmlite:\n" + f"Expected: {sorted(expected)}\n" + f" Got: {sorted(got)}\n\n" + f"Difference: {set.symmetric_difference(expected, got)}\n" + f"Only in Expected: {set.difference(expected, got)}\n" + f"Only in Got: {set.difference(got, expected)}\n") + raise AssertionError(msg) from e + + @is_wheel_package + def test_wheel_build(self): + info = llvm.config.get_sysinfo() + self.assertEqual(info['llvm_linkage_type'], "static") + self.assertEqual(info['llvm_assertions_state'], "on") + self.check_linkage(info, "wheel") + + @is_conda_package + def test_conda_build(self): + info = llvm.config.get_sysinfo() + self.assertEqual(info['llvm_linkage_type'], "static") + self.assertEqual(info['llvm_assertions_state'], "on") + + self.check_linkage(info, "conda") + if platform.system().lower() == "linux": + self.assertEqual(info['libstdcxx_linkage_type'], "static") + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_ir.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_ir.py new file mode 100644 index 0000000000000000000000000000000000000000..d51f6434367ba3eaca7717baa842bb1179a1e3fe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_ir.py @@ -0,0 +1,3194 @@ +""" +IR Construction Tests +""" + +import copy +import itertools +import pickle +import re +import textwrap +import unittest + +from . import TestCase +from llvmlite import ir +from llvmlite import binding as llvm +from llvmlite import ir_layer_typed_pointers_enabled + + +int1 = ir.IntType(1) +int8 = ir.IntType(8) +int16 = ir.IntType(16) +int32 = ir.IntType(32) +int64 = ir.IntType(64) +hlf = ir.HalfType() +flt = ir.FloatType() +dbl = ir.DoubleType() + + +class TestBase(TestCase): + """ + Utilities for IR tests. + """ + + def assertInText(self, pattern, text): + """ + Assert *pattern* is in *text*, ignoring any whitespace differences + (including newlines). + """ + + def escape(c): + if not c.isalnum() and not c.isspace(): + return '\\' + c + return c + + pattern = ''.join(map(escape, pattern)) + regex = re.sub(r'\s+', r'\\s*', pattern) + self.assertRegex(text, regex) + + def assert_ir_line(self, line, mod): + lines = [line.strip() for line in str(mod).splitlines()] + self.assertIn(line, lines) + + def assert_valid_ir(self, mod): + llvm.parse_assembly(str(mod)) + + def assert_pickle_correctly(self, irobject): + """Assert that the IR object pickles and unpickles correctly. + The IR string is equal and that their type is equal + """ + newobject = pickle.loads(pickle.dumps(irobject, protocol=-1)) + self.assertIs(irobject.__class__, newobject.__class__) + self.assertEqual(str(irobject), str(newobject)) + return newobject + + def module(self): + return ir.Module() + + def function(self, module=None, name='my_func'): + module = module or self.module() + fnty = ir.FunctionType(int32, (int32, int32, dbl, + ir.PointerType(int32))) + return ir.Function(module, fnty, name) + + def block(self, func=None, name=''): + func = func or self.function() + return func.append_basic_block(name) + + def descr(self, thing): + buf = [] + thing.descr(buf) + return "".join(buf) + + def _normalize_asm(self, asm): + asm = textwrap.dedent(asm) + # Normalize indent + asm = asm.replace("\n ", "\n ") + return asm + + def check_descr_regex(self, descr, asm): + expected = self._normalize_asm(asm) + self.assertRegex(descr, expected) + + def check_descr(self, descr, asm): + expected = self._normalize_asm(asm) + self.assertEqual(descr, expected) + + def check_block(self, block, asm): + self.check_descr(self.descr(block), asm) + + def check_block_regex(self, block, asm): + self.check_descr_regex(self.descr(block), asm) + + def check_module_body(self, module, asm): + expected = self._normalize_asm(asm) + actual = module._stringify_body() + self.assertEqual(actual.strip(), expected.strip()) + + def check_metadata(self, module, asm): + """ + Check module metadata against *asm*. + """ + expected = self._normalize_asm(asm) + actual = module._stringify_metadata() + self.assertEqual(actual.strip(), expected.strip()) + + def check_func_body(self, func, asm): + expected = self._normalize_asm(asm) + actual = self.descr(func) + actual = actual.partition('{')[2].rpartition('}')[0] + self.assertEqual(actual.strip(), expected.strip()) + + +class TestFunction(TestBase): + + proto = \ + """i32 @"my_func"(i32 %".1", i32 %".2", double %".3", ptr %".4")""" \ + if not ir_layer_typed_pointers_enabled else \ + """i32 @"my_func"(i32 %".1", i32 %".2", double %".3", i32* %".4")""" + + def test_declare(self): + # A simple declaration + func = self.function() + asm = self.descr(func).strip() + self.assertEqual(asm.strip(), "declare %s" % self.proto) + + def test_declare_attributes(self): + # Now with function attributes + func = self.function() + func.attributes.add("optsize") + func.attributes.add("alwaysinline") + func.attributes.add("convergent") + func.attributes.alignstack = 16 + tp_pers = ir.FunctionType(int8, (), var_arg=True) + pers = ir.Function(self.module(), tp_pers, '__gxx_personality_v0') + func.attributes.personality = pers + asm = self.descr(func).strip() + if not ir_layer_typed_pointers_enabled: + self.assertEqual(asm, + ("declare %s alwaysinline convergent optsize " + "alignstack(16) " + "personality ptr @\"__gxx_personality_v0\"") % + self.proto) + else: + self.assertEqual(asm, + ("declare %s alwaysinline convergent optsize " + "alignstack(16) personality " + "i8 (...)* @\"__gxx_personality_v0\"") % + self.proto) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attributes(self): + # Now with parameter attributes + func = self.function() + func.args[0].add_attribute("zeroext") + func.args[1].attributes.dereferenceable = 5 + func.args[1].attributes.dereferenceable_or_null = 10 + func.args[3].attributes.align = 4 + func.args[3].add_attribute("nonnull") + func.return_value.add_attribute("noalias") + asm = self.descr(func).strip() + if not ir_layer_typed_pointers_enabled: + self.assertEqual(asm, + """declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", ptr nonnull align 4 %".4")""" # noqa E501 + ) + else: + self.assertEqual(asm, + """declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", i32* nonnull align 4 %".4")""" # noqa E501 + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_metadata(self): + # Now with function metadata + module = self.module() + func = self.function(module) + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} !dbg !0' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_section(self): + # Test function with section + func = self.function() + func.section = "a_section" + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} section "a_section"' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_section_meta(self): + # Test function with section and metadata + module = self.module() + func = self.function(module) + func.section = "a_section" + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} section "a_section" !dbg !0' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attr_meta(self): + # Test function with attributes and metadata + module = self.module() + func = self.function(module) + func.attributes.add("alwaysinline") + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} alwaysinline !dbg !0' + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attr_section(self): + # Test function with attributes and section + func = self.function() + func.attributes.add("optsize") + func.section = "a_section" + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} optsize section "a_section"') + # Check pickling + self.assert_pickle_correctly(func) + + def test_function_attr_section_meta(self): + # Test function with attributes, section and metadata + module = self.module() + func = self.function(module) + func.attributes.add("alwaysinline") + func.section = "a_section" + func.set_metadata('dbg', module.add_metadata([])) + asm = self.descr(func).strip() + self.assertEqual(asm, + f'declare {self.proto} alwaysinline section "a_section" !dbg !0' # noqa E501 + ) + # Check pickling + self.assert_pickle_correctly(func) + + def test_define(self): + # A simple definition + func = self.function() + func.attributes.add("alwaysinline") + block = func.append_basic_block('my_block') + builder = ir.IRBuilder(block) + builder.ret_void() + asm = self.descr(func) + self.check_descr(asm, """\ + define {proto} alwaysinline + {{ + my_block: + ret void + }} + """.format(proto=self.proto)) + + def test_declare_intrinsics(self): + module = self.module() + pint8 = int8.as_pointer() + + powi = module.declare_intrinsic('llvm.powi', [dbl]) + memset = module.declare_intrinsic('llvm.memset', [pint8, int32]) + memcpy = module.declare_intrinsic('llvm.memcpy', [pint8, pint8, int32]) + assume = module.declare_intrinsic('llvm.assume') + self.check_descr(self.descr(powi).strip(), """\ + declare double @"llvm.powi.f64"(double %".1", i32 %".2")""") + if not ir_layer_typed_pointers_enabled: + self.check_descr(self.descr(memset).strip(), """\ + declare void @"llvm.memset.p0.i32"(ptr %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501 + self.check_descr(self.descr(memcpy).strip(), """\ + declare void @"llvm.memcpy.p0.p0.i32"(ptr %".1", ptr %".2", i32 %".3", i1 %".4")""") # noqa E501 + else: + self.check_descr(self.descr(memset).strip(), """\ + declare void @"llvm.memset.p0i8.i32"(i8* %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501 + self.check_descr(self.descr(memcpy).strip(), """\ + declare void @"llvm.memcpy.p0i8.p0i8.i32"(i8* %".1", i8* %".2", i32 %".3", i1 %".4")""") # noqa E501 + self.check_descr(self.descr(assume).strip(), """\ + declare void @"llvm.assume"(i1 %".1")""") + + def test_redeclare_intrinsic(self): + module = self.module() + powi = module.declare_intrinsic('llvm.powi', [dbl]) + powi2 = module.declare_intrinsic('llvm.powi', [dbl]) + self.assertIs(powi, powi2) + + def test_pickling(self): + fn = self.function() + self.assert_pickle_correctly(fn) + + def test_alwaysinline_noinline_disallowed(self): + module = self.module() + func = self.function(module) + func.attributes.add('alwaysinline') + + msg = "Can't have alwaysinline and noinline" + with self.assertRaisesRegex(ValueError, msg): + func.attributes.add('noinline') + + def test_noinline_alwaysinline_disallowed(self): + module = self.module() + func = self.function(module) + func.attributes.add('noinline') + + msg = "Can't have alwaysinline and noinline" + with self.assertRaisesRegex(ValueError, msg): + func.attributes.add('alwaysinline') + + +class TestIR(TestBase): + + def test_unnamed_metadata(self): + # An unnamed metadata node + mod = self.module() + mod.add_metadata([int32(123), int8(42)]) + self.assert_ir_line("!0 = !{ i32 123, i8 42 }", mod) + self.assert_valid_ir(mod) + + def test_unnamed_metadata_2(self): + # Several unnamed metadata nodes + mod = self.module() + # First node has a literal metadata string + m0 = mod.add_metadata([int32(123), "kernel"]) + # Second node refers to the first one + m1 = mod.add_metadata([int64(456), m0]) + # Third node is the same as the second one + m2 = mod.add_metadata([int64(456), m0]) + self.assertIs(m2, m1) + # Fourth node refers to the first three + mod.add_metadata([m0, m1, m2]) + self.assert_ir_line('!0 = !{ i32 123, !"kernel" }', mod) + self.assert_ir_line('!1 = !{ i64 456, !0 }', mod) + self.assert_ir_line('!2 = !{ !0, !1, !1 }', mod) + + def test_unnamed_metadata_3(self): + # Passing nested metadata as a sequence + mod = self.module() + mod.add_metadata([int32(123), [int32(456)], [int32(789)], [int32(456)]]) + self.assert_ir_line('!0 = !{ i32 456 }', mod) + self.assert_ir_line('!1 = !{ i32 789 }', mod) + self.assert_ir_line('!2 = !{ i32 123, !0, !1, !0 }', mod) + + def test_metadata_string(self): + # Escaping contents of a metadata string + mod = self.module() + mod.add_metadata(["\"\\$"]) + self.assert_ir_line('!0 = !{ !"\\22\\5c$" }', mod) + + def test_named_metadata(self): + # Add a named metadata node and add metadata values to it + mod = self.module() + m0 = mod.add_metadata([int32(123)]) + m1 = mod.add_metadata([int64(456)]) + nmd = mod.add_named_metadata("foo") + nmd.add(m0) + nmd.add(m1) + nmd.add(m0) + self.assert_ir_line("!foo = !{ !0, !1, !0 }", mod) + self.assert_valid_ir(mod) + # Check get_named_metadata() + self.assertIs(nmd, mod.get_named_metadata("foo")) + with self.assertRaises(KeyError): + mod.get_named_metadata("bar") + + def test_named_metadata_2(self): + # Add and set named metadata through a single add_named_metadata() call + mod = self.module() + m0 = mod.add_metadata([int32(123)]) + mod.add_named_metadata("foo", m0) + mod.add_named_metadata("foo", [int64(456)]) + mod.add_named_metadata("foo", ["kernel"]) + mod.add_named_metadata("bar", []) + self.assert_ir_line("!foo = !{ !0, !1, !2 }", mod) + self.assert_ir_line("!0 = !{ i32 123 }", mod) + self.assert_ir_line("!1 = !{ i64 456 }", mod) + self.assert_ir_line('!2 = !{ !"kernel" }', mod) + self.assert_ir_line("!bar = !{ !3 }", mod) + self.assert_ir_line('!3 = !{ }', mod) + self.assert_valid_ir(mod) + + def test_metadata_null(self): + # A null metadata (typed) value + mod = self.module() + mod.add_metadata([int32.as_pointer()(None)]) + if not ir_layer_typed_pointers_enabled: + self.assert_ir_line("!0 = !{ ptr null }", mod) + else: + self.assert_ir_line("!0 = !{ i32* null }", mod) + self.assert_valid_ir(mod) + # A null metadata (untyped) value + mod = self.module() + mod.add_metadata([None, int32(123)]) + self.assert_ir_line("!0 = !{ null, i32 123 }", mod) + self.assert_valid_ir(mod) + + def test_debug_info(self): + # Add real world-looking debug information to a module + # (with various value types) + mod = self.module() + di_file = mod.add_debug_info("DIFile", { + "filename": "foo", + "directory": "bar", + }) + di_func_type = mod.add_debug_info("DISubroutineType", { + # None as `null` + "types": mod.add_metadata([None]), + }) + di_compileunit = mod.add_debug_info("DICompileUnit", { + "language": ir.DIToken("DW_LANG_Python"), + "file": di_file, + "producer": "ARTIQ", + "runtimeVersion": 0, + "isOptimized": True, + }, is_distinct=True) + mod.add_debug_info("DISubprogram", { + "name": "my_func", + "file": di_file, + "line": 11, + "type": di_func_type, + "isLocal": False, + "unit": di_compileunit, + }, is_distinct=True) + + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIFile(directory: "bar", filename: "foo")', + strmod) + self.assert_ir_line('!1 = !{ null }', strmod) + self.assert_ir_line('!2 = !DISubroutineType(types: !1)', strmod) + # self.assert_ir_line('!4 = !{ !3 }', strmod) + self.assert_ir_line('!3 = distinct !DICompileUnit(file: !0, ' + 'isOptimized: true, language: DW_LANG_Python, ' + 'producer: "ARTIQ", runtimeVersion: 0)', + strmod) + self.assert_ir_line('!4 = distinct !DISubprogram(file: !0, isLocal: ' + 'false, line: 11, name: "my_func", type: !2, unit: ' + '!3)', + strmod) + self.assert_valid_ir(mod) + + def test_debug_info_2(self): + # Identical debug info nodes should be merged + mod = self.module() + di1 = mod.add_debug_info("DIFile", + {"filename": "foo", + "directory": "bar", + }) + di2 = mod.add_debug_info("DIFile", + {"filename": "foo", + "directory": "bar", + }) + di3 = mod.add_debug_info("DIFile", + {"filename": "bar", + "directory": "foo", + }) + di4 = mod.add_debug_info("DIFile", + {"filename": "foo", + "directory": "bar", + }, is_distinct=True) + self.assertIs(di1, di2) + self.assertEqual(len({di1, di2, di3, di4}), 3) + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIFile(directory: "bar", filename: "foo")', + strmod) + self.assert_ir_line('!1 = !DIFile(directory: "foo", filename: "bar")', + strmod) + self.assert_ir_line('!2 = distinct !DIFile(directory: "bar", filename: ' + '"foo")', strmod) + self.assert_valid_ir(mod) + + def test_debug_info_3(self): + # Identical DIBasicType metadata nodes should be merged + mod = self.module() + di1 = mod.add_debug_info("DIBasicType", { + "name": "i8", + "size": 8, + "encoding": ir.DIToken("DW_ATE_unsigned") + }) + di2 = mod.add_debug_info("DIBasicType", { + "name": "i8", + "size": 8, + "encoding": ir.DIToken("DW_ATE_unsigned") + }) + di3 = mod.add_debug_info("DIBasicType", { + "name": "i32", + "size": 32, + "encoding": ir.DIToken("DW_ATE_unsigned") + }) + di4 = mod.add_debug_info("DIBasicType", { + "name": "i8", + "size": 8, + "encoding": ir.DIToken("DW_ATE_unsigned") + }) + di5 = mod.add_debug_info("DIBasicType", { + "name": "i8", + "size": 8, + "encoding": ir.DIToken("DW_ATE_unsigned") + }) + di6 = mod.add_debug_info("DIBasicType", { + "name": "i32", + "size": 32, + "encoding": ir.DIToken("DW_ATE_unsigned") + }) + di7 = mod.add_debug_info("DIBasicType", { + "name": "i64", + "size": 64, + "encoding": ir.DIToken("DW_ATE_signed") + }) + di8 = mod.add_debug_info("DIBasicType", { + "name": "i64", + "size": 64, + "encoding": ir.DIToken("DW_ATE_signed") + }) + di9 = mod.add_debug_info("DIBasicType", { + "name": "i64", + "size": 64, + "encoding": ir.DIToken("DW_ATE_signed") + }) + self.assertIs(di1, di2) + self.assertIs(di1, di4) + self.assertIs(di1, di5) + self.assertIs(di3, di6) + self.assertIs(di7, di8) + self.assertIs(di7, di9) + self.assertEqual(len({di1, di2, di3, di4, di5, di6, di7, di8, di9}), 3) + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIBasicType(encoding: DW_ATE_unsigned, ' + 'name: "i8", size: 8)', strmod) + self.assert_ir_line('!1 = !DIBasicType(encoding: DW_ATE_unsigned, ' + 'name: "i32", size: 32)', strmod) + self.assert_ir_line('!2 = !DIBasicType(encoding: DW_ATE_signed, ' + 'name: "i64", size: 64)', strmod) + self.assert_valid_ir(mod) + + def test_debug_info_4(self): + # Typed constant as output value of debug info fields + mod = self.module() + # Create base types first + di_base_i32 = mod.add_debug_info("DIBasicType", { + "name": "int32", + "size": 32, + "encoding": ir.DIToken("DW_ATE_signed") + }) + di_base_i8 = mod.add_debug_info("DIBasicType", { + "name": "int8", + "size": 8, + "encoding": ir.DIToken("DW_ATE_signed") + }) + # Create debug info nodes with typed constants + mod.add_debug_info("DIDerivedType", { + "tag": ir.DIToken("DW_TAG_member"), + "name": "field_i32", + "baseType": di_base_i32, + "size": 32, + "extraData": ir.IntType(32)(1) + }) + mod.add_debug_info("DIDerivedType", { + "tag": ir.DIToken("DW_TAG_member"), + "name": "field_i8", + "baseType": di_base_i8, + "size": 8, + "extraData": ir.IntType(8)(2) + }) + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIBasicType(encoding: DW_ATE_signed, ' + 'name: "int32", size: 32)', strmod) + self.assert_ir_line('!1 = !DIBasicType(encoding: DW_ATE_signed, ' + 'name: "int8", size: 8)', strmod) + self.assert_ir_line( + '!2 = !DIDerivedType(baseType: !0, extraData: i32 1, ' + 'name: "field_i32", size: 32, tag: DW_TAG_member)', strmod) + self.assert_ir_line( + '!3 = !DIDerivedType(baseType: !1, extraData: i8 2, ' + 'name: "field_i8", size: 8, tag: DW_TAG_member)', strmod) + self.assert_valid_ir(mod) + + def test_debug_info_gvar(self): + # This test defines a module with a global variable named 'gvar'. + # When the module is compiled and linked with a main function, gdb can + # be used to interpret and print the the value of 'gvar'. + mod = self.module() + + gvar = ir.GlobalVariable(mod, ir.FloatType(), 'gvar') + gvar.initializer = ir.Constant(ir.FloatType(), 42) + + di_float = mod.add_debug_info("DIBasicType", { + "name": "float", + "size": 32, + "encoding": ir.DIToken("DW_ATE_float") + }) + di_gvar = mod.add_debug_info("DIGlobalVariableExpression", { + "expr": mod.add_debug_info("DIExpression", {}), + "var": mod.add_debug_info("DIGlobalVariable", { + "name": gvar.name, + "type": di_float, + "isDefinition": True + }, is_distinct=True) + }) + gvar.set_metadata('dbg', di_gvar) + + # Check output + strmod = str(mod) + self.assert_ir_line('!0 = !DIBasicType(encoding: DW_ATE_float, ' + 'name: "float", size: 32)', strmod) + self.assert_ir_line('!1 = !DIExpression()', strmod) + self.assert_ir_line('!2 = distinct !DIGlobalVariable(isDefinition: ' + 'true, name: "gvar", type: !0)', strmod) + self.assert_ir_line('!3 = !DIGlobalVariableExpression(expr: !1, ' + 'var: !2)', strmod) + self.assert_ir_line('@"gvar" = global float 0x4045000000000000, ' + '!dbg !3', strmod) + + # The remaining debug info is not part of the automated test, but + # can be used to produce an object file that can be loaded into a + # debugger to print the value of gvar. This can be done by printing the + # module then compiling it with clang and inspecting with gdb: + # + # clang test_debug_info_gvar.ll -c + # printf "file test_debug_info_gvar.o \n p gvar" | gdb + # + # Which should result in the output: + # + # (gdb) $1 = 42 + + dver = [ir.IntType(32)(2), 'Dwarf Version', ir.IntType(32)(4)] + diver = [ir.IntType(32)(2), 'Debug Info Version', ir.IntType(32)(3)] + dver = mod.add_metadata(dver) + diver = mod.add_metadata(diver) + flags = mod.add_named_metadata('llvm.module.flags') + flags.add(dver) + flags.add(diver) + + di_file = mod.add_debug_info("DIFile", { + "filename": "foo", + "directory": "bar", + }) + di_cu = mod.add_debug_info("DICompileUnit", { + "language": ir.DIToken("DW_LANG_Python"), + "file": di_file, + 'emissionKind': ir.DIToken('FullDebug'), + "globals": mod.add_metadata([di_gvar]) + }, is_distinct=True) + mod.add_named_metadata('llvm.dbg.cu', di_cu) + + def test_debug_info_unicode_string(self): + mod = self.module() + mod.add_debug_info("DILocalVariable", {"name": "a∆"}) + # Check output + strmod = str(mod) + # The unicode character is utf8 encoded with \XX format, where XX is hex + name = ''.join(map(lambda x: f"\\{x:02x}", "∆".encode())) + self.assert_ir_line(f'!0 = !DILocalVariable(name: "a{name}")', strmod) + + def test_inline_assembly(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + asmty = ir.FunctionType(int32, [int32]) + asm = ir.InlineAsm(asmty, "mov $1, $2", "=r,r", side_effect=True) + builder.call(asm, [int32(123)]) + builder.ret_void() + pat = 'call i32 asm sideeffect "mov $1, $2", "=r,r"( i32 123 )' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + def test_builder_asm(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + asmty = ir.FunctionType(int32, [int32]) + builder.asm(asmty, "mov $1, $2", "=r,r", [int32(123)], side_effect=True) + builder.ret_void() + pat = 'call i32 asm sideeffect "mov $1, $2", "=r,r" ( i32 123 )' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + def test_builder_load_reg(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + builder.load_reg(ir.IntType(64), "rax") + builder.ret_void() + pat = 'call i64 asm "", "={rax}"' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + def test_builder_store_reg(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + builder = ir.IRBuilder(foo.append_basic_block('')) + builder.store_reg(int64(123), ir.IntType(64), "rax") + builder.ret_void() + pat = 'call void asm sideeffect "", "{rax}" ( i64 123 )' + self.assertInText(pat, str(mod)) + self.assert_valid_ir(mod) + + +class TestGlobalValues(TestBase): + + def test_globals_access(self): + mod = self.module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo') + ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'bar') + globdouble = ir.GlobalVariable(mod, ir.DoubleType(), 'globdouble') + self.assertEqual(mod.get_global('foo'), foo) + self.assertEqual(mod.get_global('globdouble'), globdouble) + with self.assertRaises(KeyError): + mod.get_global('kkk') + # Globals should have a useful repr() + if not ir_layer_typed_pointers_enabled: + self.assertEqual(repr(globdouble), + "") + else: + self.assertEqual( + repr(globdouble), + "") + + def test_functions_global_values_access(self): + """ + Accessing functions and global values through Module.functions + and Module.global_values. + """ + mod = self.module() + fty = ir.FunctionType(ir.VoidType(), []) + foo = ir.Function(mod, fty, 'foo') + bar = ir.Function(mod, fty, 'bar') + globdouble = ir.GlobalVariable(mod, ir.DoubleType(), 'globdouble') + self.assertEqual(set(mod.functions), set((foo, bar))) + self.assertEqual(set(mod.global_values), set((foo, bar, globdouble))) + + def test_global_variables_ir(self): + """ + IR serialization of global variables. + """ + mod = self.module() + # the following have side effects and write to self.module() + a = ir.GlobalVariable(mod, int8, 'a') # noqa F841 + b = ir.GlobalVariable(mod, int8, 'b', addrspace=42) # noqa F841 + # Initialized global variable doesn't default to "external" + c = ir.GlobalVariable(mod, int32, 'c') + c.initializer = int32(123) + d = ir.GlobalVariable(mod, int32, 'd') + d.global_constant = True + # Non-external linkage implies default "undef" initializer + e = ir.GlobalVariable(mod, int32, 'e') + e.linkage = "internal" + f = ir.GlobalVariable(mod, int32, 'f', addrspace=456) + f.unnamed_addr = True + g = ir.GlobalVariable(mod, int32, 'g') + g.linkage = "internal" + g.initializer = int32(123) + g.align = 16 + h = ir.GlobalVariable(mod, int32, 'h') + h.linkage = "internal" + h.initializer = int32(123) + h.section = "h_section" + i = ir.GlobalVariable(mod, int32, 'i') + i.linkage = "internal" + i.initializer = int32(456) + i.align = 8 + i.section = "i_section" + self.check_module_body(mod, """\ + @"a" = external global i8 + @"b" = external addrspace(42) global i8 + @"c" = global i32 123 + @"d" = external constant i32 + @"e" = internal global i32 undef + @"f" = external unnamed_addr addrspace(456) global i32 + @"g" = internal global i32 123, align 16 + @"h" = internal global i32 123, section "h_section" + @"i" = internal global i32 456, section "i_section", align 8 + """) + + def test_pickle(self): + mod = self.module() + self.assert_pickle_correctly(mod) + + +class TestBlock(TestBase): + + def test_attributes(self): + func = self.function() + block = ir.Block(parent=func, name='start') + self.assertIs(block.parent, func) + self.assertFalse(block.is_terminated) + + def test_descr(self): + block = self.block(name='my_block') + self.assertEqual(self.descr(block), "my_block:\n") + block.instructions.extend(['a', 'b']) + self.assertEqual(self.descr(block), "my_block:\n a\n b\n") + + def test_replace(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.add(a, b, 'c') + d = builder.sub(a, b, 'd') + builder.mul(d, b, 'e') + f = ir.Instruction(block, a.type, 'sdiv', (c, b), 'f') + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"d" = sub i32 %".1", %".2" + %"e" = mul i32 %"d", %".2" + """) + block.replace(d, f) + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"f" = sdiv i32 %"c", %".2" + %"e" = mul i32 %"f", %".2" + """) + + def test_repr(self): + """ + Blocks should have a useful repr() + """ + func = self.function() + block = ir.Block(parent=func, name='start') + self.assertEqual(repr(block), "") + + +class TestBuildInstructions(TestBase): + """ + Test IR generation of LLVM instructions through the IRBuilder class. + """ + + maxDiff = 4000 + + def test_simple(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + inst = builder.add(a, b, 'res') + self.check_block(block, """\ + my_block: + %"res" = add i32 %".1", %".2" + """) + # Instructions should have a useful repr() + self.assertEqual(repr(inst), + ", " + ")>") + + def test_binops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, ff = builder.function.args[:3] + builder.add(a, b, 'c') + builder.fadd(a, b, 'd') + builder.sub(a, b, 'e') + builder.fsub(a, b, 'f') + builder.mul(a, b, 'g') + builder.fmul(a, b, 'h') + builder.udiv(a, b, 'i') + builder.sdiv(a, b, 'j') + builder.fdiv(a, b, 'k') + builder.urem(a, b, 'l') + builder.srem(a, b, 'm') + builder.frem(a, b, 'n') + builder.or_(a, b, 'o') + builder.and_(a, b, 'p') + builder.xor(a, b, 'q') + builder.shl(a, b, 'r') + builder.ashr(a, b, 's') + builder.lshr(a, b, 't') + with self.assertRaises(ValueError) as cm: + builder.add(a, ff) + self.assertEqual(str(cm.exception), + "Operands must be the same type, got (i32, double)") + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"d" = fadd i32 %".1", %".2" + %"e" = sub i32 %".1", %".2" + %"f" = fsub i32 %".1", %".2" + %"g" = mul i32 %".1", %".2" + %"h" = fmul i32 %".1", %".2" + %"i" = udiv i32 %".1", %".2" + %"j" = sdiv i32 %".1", %".2" + %"k" = fdiv i32 %".1", %".2" + %"l" = urem i32 %".1", %".2" + %"m" = srem i32 %".1", %".2" + %"n" = frem i32 %".1", %".2" + %"o" = or i32 %".1", %".2" + %"p" = and i32 %".1", %".2" + %"q" = xor i32 %".1", %".2" + %"r" = shl i32 %".1", %".2" + %"s" = ashr i32 %".1", %".2" + %"t" = lshr i32 %".1", %".2" + """) + + def test_binop_flags(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + # As tuple + builder.add(a, b, 'c', flags=('nuw',)) + # and as list + builder.sub(a, b, 'd', flags=['nuw', 'nsw']) + self.check_block(block, """\ + my_block: + %"c" = add nuw i32 %".1", %".2" + %"d" = sub nuw nsw i32 %".1", %".2" + """) + + def test_binop_fastmath_flags(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + # As tuple + builder.fadd(a, b, 'c', flags=('fast',)) + # and as list + builder.fsub(a, b, 'd', flags=['ninf', 'nsz']) + self.check_block(block, """\ + my_block: + %"c" = fadd fast i32 %".1", %".2" + %"d" = fsub ninf nsz i32 %".1", %".2" + """) + + def test_binops_with_overflow(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.sadd_with_overflow(a, b, 'c') + builder.smul_with_overflow(a, b, 'd') + builder.ssub_with_overflow(a, b, 'e') + builder.uadd_with_overflow(a, b, 'f') + builder.umul_with_overflow(a, b, 'g') + builder.usub_with_overflow(a, b, 'h') + self.check_block(block, """\ +my_block: + %"c" = call {i32, i1} @"llvm.sadd.with.overflow.i32"(i32 %".1", i32 %".2") + %"d" = call {i32, i1} @"llvm.smul.with.overflow.i32"(i32 %".1", i32 %".2") + %"e" = call {i32, i1} @"llvm.ssub.with.overflow.i32"(i32 %".1", i32 %".2") + %"f" = call {i32, i1} @"llvm.uadd.with.overflow.i32"(i32 %".1", i32 %".2") + %"g" = call {i32, i1} @"llvm.umul.with.overflow.i32"(i32 %".1", i32 %".2") + %"h" = call {i32, i1} @"llvm.usub.with.overflow.i32"(i32 %".1", i32 %".2") + """) + + def test_unary_ops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, c = builder.function.args[:3] + builder.neg(a, 'd') + builder.not_(b, 'e') + builder.fneg(c, 'f') + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"d" = sub i32 0, %".1" + %"e" = xor i32 %".2", -1 + %"f" = fneg double %".3" + """) + + def test_replace_operand(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + undef1 = ir.Constant(ir.IntType(32), ir.Undefined) + undef2 = ir.Constant(ir.IntType(32), ir.Undefined) + c = builder.add(undef1, undef2, 'c') + self.check_block(block, """\ + my_block: + %"c" = add i32 undef, undef + """) + c.replace_usage(undef1, a) + c.replace_usage(undef2, b) + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + """) + + def test_integer_comparisons(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.icmp_unsigned('==', a, b, 'c') + builder.icmp_unsigned('!=', a, b, 'd') + builder.icmp_unsigned('<', a, b, 'e') + builder.icmp_unsigned('<=', a, b, 'f') + builder.icmp_unsigned('>', a, b, 'g') + builder.icmp_unsigned('>=', a, b, 'h') + builder.icmp_signed('==', a, b, 'i') + builder.icmp_signed('!=', a, b, 'j') + builder.icmp_signed('<', a, b, 'k') + builder.icmp_signed('<=', a, b, 'l') + builder.icmp_signed('>', a, b, 'm') + builder.icmp_signed('>=', a, b, 'n') + with self.assertRaises(ValueError): + builder.icmp_signed('uno', a, b, 'zz') + with self.assertRaises(ValueError): + builder.icmp_signed('foo', a, b, 'zz') + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = icmp eq i32 %".1", %".2" + %"d" = icmp ne i32 %".1", %".2" + %"e" = icmp ult i32 %".1", %".2" + %"f" = icmp ule i32 %".1", %".2" + %"g" = icmp ugt i32 %".1", %".2" + %"h" = icmp uge i32 %".1", %".2" + %"i" = icmp eq i32 %".1", %".2" + %"j" = icmp ne i32 %".1", %".2" + %"k" = icmp slt i32 %".1", %".2" + %"l" = icmp sle i32 %".1", %".2" + %"m" = icmp sgt i32 %".1", %".2" + %"n" = icmp sge i32 %".1", %".2" + """) + + def test_float_comparisons(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.fcmp_ordered('==', a, b, 'c') + builder.fcmp_ordered('!=', a, b, 'd') + builder.fcmp_ordered('<', a, b, 'e') + builder.fcmp_ordered('<=', a, b, 'f') + builder.fcmp_ordered('>', a, b, 'g') + builder.fcmp_ordered('>=', a, b, 'h') + builder.fcmp_unordered('==', a, b, 'i') + builder.fcmp_unordered('!=', a, b, 'j') + builder.fcmp_unordered('<', a, b, 'k') + builder.fcmp_unordered('<=', a, b, 'l') + builder.fcmp_unordered('>', a, b, 'm') + builder.fcmp_unordered('>=', a, b, 'n') + # fcmp_ordered and fcmp_unordered are the same for these cases + builder.fcmp_ordered('ord', a, b, 'u') + builder.fcmp_ordered('uno', a, b, 'v') + builder.fcmp_unordered('ord', a, b, 'w') + builder.fcmp_unordered('uno', a, b, 'x') + builder.fcmp_unordered('olt', a, b, 'y', + flags=['nnan', 'ninf', 'nsz', 'arcp', 'fast']) + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = fcmp oeq i32 %".1", %".2" + %"d" = fcmp one i32 %".1", %".2" + %"e" = fcmp olt i32 %".1", %".2" + %"f" = fcmp ole i32 %".1", %".2" + %"g" = fcmp ogt i32 %".1", %".2" + %"h" = fcmp oge i32 %".1", %".2" + %"i" = fcmp ueq i32 %".1", %".2" + %"j" = fcmp une i32 %".1", %".2" + %"k" = fcmp ult i32 %".1", %".2" + %"l" = fcmp ule i32 %".1", %".2" + %"m" = fcmp ugt i32 %".1", %".2" + %"n" = fcmp uge i32 %".1", %".2" + %"u" = fcmp ord i32 %".1", %".2" + %"v" = fcmp uno i32 %".1", %".2" + %"w" = fcmp ord i32 %".1", %".2" + %"x" = fcmp uno i32 %".1", %".2" + %"y" = fcmp nnan ninf nsz arcp fast olt i32 %".1", %".2" + """) + + def test_misc_ops(self): + block = self.block(name='my_block') + t = ir.Constant(int1, True) + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.select(t, a, b, 'c', flags=('arcp', 'nnan')) + self.assertFalse(block.is_terminated) + builder.unreachable() + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + %"c" = select arcp nnan i1 true, i32 %".1", i32 %".2" + unreachable + """) + + def test_phi(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + bb2 = builder.function.append_basic_block('b2') + bb3 = builder.function.append_basic_block('b3') + phi = builder.phi(int32, 'my_phi', flags=('fast',)) + phi.add_incoming(a, bb2) + phi.add_incoming(b, bb3) + self.assertFalse(block.is_terminated) + self.check_block(block, """\ + my_block: + %"my_phi" = phi fast i32 [%".1", %"b2"], [%".2", %"b3"] + """) + + def test_mem_ops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, z = builder.function.args[:3] + c = builder.alloca(int32, name='c') + d = builder.alloca(int32, size=42, name='d') # noqa F841 + e = builder.alloca(dbl, size=a, name='e') + e.align = 8 + self.assertEqual(e.type, ir.PointerType(dbl)) + ee = builder.store(z, e) + self.assertEqual(ee.type, ir.VoidType()) + f = builder.store(b, c) + self.assertEqual(f.type, ir.VoidType()) + g = builder.load(c, 'g') + self.assertEqual(g.type, int32) + # With alignment + h = builder.store(b, c, align=1) + self.assertEqual(h.type, ir.VoidType()) + i = builder.load(c, 'i', align=1) + self.assertEqual(i.type, int32) + # Atomics + j = builder.store_atomic(b, c, ordering="seq_cst", align=4) + self.assertEqual(j.type, ir.VoidType()) + k = builder.load_atomic(c, ordering="seq_cst", align=4, name='k') + self.assertEqual(k.type, int32) + if not ir_layer_typed_pointers_enabled: + ptr = ir.Constant(ir.PointerType(), None) + else: + ptr = ir.Constant(ir.PointerType(int32), None) + builder.store(ir.Constant(int32, 5), ptr) + # Not pointer types + with self.assertRaises(TypeError): + builder.store(b, a) + with self.assertRaises(TypeError): + builder.load(b) + # Mismatching pointer type + with self.assertRaises(TypeError) as cm: + builder.store(b, e) + + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(cm.exception), + "cannot store i32 to ptr: mismatching types") + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = alloca i32, i32 42 + %"e" = alloca double, i32 %".1", align 8 + store double %".3", ptr %"e" + store i32 %".2", ptr %"c" + %"g" = load i32, ptr %"c" + store i32 %".2", ptr %"c", align 1 + %"i" = load i32, ptr %"c", align 1 + store atomic i32 %".2", ptr %"c" seq_cst, align 4 + %"k" = load atomic i32, ptr %"c" seq_cst, align 4 + store i32 5, ptr null + """) + else: + self.assertEqual(str(cm.exception), + "cannot store i32 to double*: mismatching types") + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = alloca i32, i32 42 + %"e" = alloca double, i32 %".1", align 8 + store double %".3", double* %"e" + store i32 %".2", i32* %"c" + %"g" = load i32, i32* %"c" + store i32 %".2", i32* %"c", align 1 + %"i" = load i32, i32* %"c", align 1 + store atomic i32 %".2", i32* %"c" seq_cst, align 4 + %"k" = load atomic i32, i32* %"c" seq_cst, align 4 + store i32 5, i32* null + """) + + def test_gep(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.alloca(ir.PointerType(int32), name='c') + d = builder.gep(c, [ir.Constant(int32, 5), a], name='d') + self.assertEqual(d.type, ir.PointerType(int32)) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca ptr + %"d" = getelementptr ptr, ptr %"c", i32 5, i32 %".1" + """) + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32* + %"d" = getelementptr i32*, i32** %"c", i32 5, i32 %".1" + """) + # XXX test with more complex types + + def test_gep_castinstr(self): + # similar to: + # numba::runtime::nrtdynmod.py_define_nrt_meminfo_data() + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + int8ptr = int8.as_pointer() + ls = ir.LiteralStructType([int64, int8ptr, int8ptr, int8ptr, int64]) + d = builder.bitcast(a, ls.as_pointer(), name='d') + e = builder.gep(d, [ir.Constant(int32, x) for x in [0, 3]], name='e') + self.assertEqual(e.type, ir.PointerType(int8ptr)) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to ptr + %"e" = getelementptr {i64, ptr, ptr, ptr, i64}, ptr %"d", i32 0, i32 3 + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to {i64, i8*, i8*, i8*, i64}* + %"e" = getelementptr {i64, i8*, i8*, i8*, i64}, {i64, i8*, i8*, i8*, i64}* %"d", i32 0, i32 3 + """) # noqa E501 + + def test_gep_castinstr_addrspace(self): + # similar to: + # numba::runtime::nrtdynmod.py_define_nrt_meminfo_data() + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + addrspace = 4 + int8ptr = int8.as_pointer() + ls = ir.LiteralStructType([int64, int8ptr, int8ptr, int8ptr, int64]) + d = builder.bitcast(a, ls.as_pointer(addrspace=addrspace), name='d') + e = builder.gep(d, [ir.Constant(int32, x) for x in [0, 3]], name='e') + self.assertEqual(e.type.addrspace, addrspace) + self.assertEqual(e.type, ir.PointerType(int8ptr, addrspace=addrspace)) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to ptr addrspace(4) + %"e" = getelementptr {i64, ptr, ptr, ptr, i64}, ptr addrspace(4) %"d", i32 0, i32 3 + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"d" = bitcast i32 %".1" to {i64, i8*, i8*, i8*, i64} addrspace(4)* + %"e" = getelementptr {i64, i8*, i8*, i8*, i64}, {i64, i8*, i8*, i8*, i64} addrspace(4)* %"d", i32 0, i32 3 + """) # noqa E501 + + def test_gep_addrspace(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + addrspace = 4 + c = builder.alloca(ir.PointerType(int32, addrspace=addrspace), name='c') + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c.type), 'ptr') + else: + self.assertEqual(str(c.type), 'i32 addrspace(4)**') + self.assertEqual(c.type.pointee.addrspace, addrspace) + d = builder.gep(c, [ir.Constant(int32, 5), a], name='d') + self.assertEqual(d.type.addrspace, addrspace) + e = builder.gep(d, [ir.Constant(int32, 10)], name='e') + self.assertEqual(e.type.addrspace, addrspace) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca ptr addrspace(4) + %"d" = getelementptr ptr addrspace(4), ptr %"c", i32 5, i32 %".1" + %"e" = getelementptr i32, ptr addrspace(4) %"d", i32 10 + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32 addrspace(4)* + %"d" = getelementptr i32 addrspace(4)*, i32 addrspace(4)** %"c", i32 5, i32 %".1" + %"e" = getelementptr i32, i32 addrspace(4)* %"d", i32 10 + """) # noqa E501 + + def test_extract_insert_value(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + tp_inner = ir.LiteralStructType([int32, int1]) + tp_outer = ir.LiteralStructType([int8, tp_inner]) + c_inner = ir.Constant(tp_inner, (ir.Constant(int32, 4), + ir.Constant(int1, True))) + # Flat structure + c = builder.extract_value(c_inner, 0, name='c') # noqa F841 + d = builder.insert_value(c_inner, a, 0, name='d') # noqa F841 + e = builder.insert_value(d, ir.Constant(int1, False), 1, name='e') # noqa F841 E501 + self.assertEqual(d.type, tp_inner) + self.assertEqual(e.type, tp_inner) + # Nested structure + p_outer = builder.alloca(tp_outer, name='ptr') + j = builder.load(p_outer, name='j') + k = builder.extract_value(j, 0, name='k') + l = builder.extract_value(j, 1, name='l') + m = builder.extract_value(j, (1, 0), name='m') + n = builder.extract_value(j, (1, 1), name='n') + o = builder.insert_value(j, l, 1, name='o') + p = builder.insert_value(j, a, (1, 0), name='p') + self.assertEqual(k.type, int8) + self.assertEqual(l.type, tp_inner) + self.assertEqual(m.type, int32) + self.assertEqual(n.type, int1) + self.assertEqual(o.type, tp_outer) + self.assertEqual(p.type, tp_outer) + + with self.assertRaises(TypeError): + # Not an aggregate + builder.extract_value(p_outer, 0) + with self.assertRaises(TypeError): + # Indexing too deep + builder.extract_value(c_inner, (0, 0)) + with self.assertRaises(TypeError): + # Index out of structure bounds + builder.extract_value(c_inner, 5) + with self.assertRaises(TypeError): + # Not an aggregate + builder.insert_value(a, b, 0) + with self.assertRaises(TypeError): + # Replacement value has the wrong type + builder.insert_value(c_inner, a, 1) + + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = extractvalue {i32, i1} {i32 4, i1 true}, 0 + %"d" = insertvalue {i32, i1} {i32 4, i1 true}, i32 %".1", 0 + %"e" = insertvalue {i32, i1} %"d", i1 false, 1 + %"ptr" = alloca {i8, {i32, i1}} + %"j" = load {i8, {i32, i1}}, ptr %"ptr" + %"k" = extractvalue {i8, {i32, i1}} %"j", 0 + %"l" = extractvalue {i8, {i32, i1}} %"j", 1 + %"m" = extractvalue {i8, {i32, i1}} %"j", 1, 0 + %"n" = extractvalue {i8, {i32, i1}} %"j", 1, 1 + %"o" = insertvalue {i8, {i32, i1}} %"j", {i32, i1} %"l", 1 + %"p" = insertvalue {i8, {i32, i1}} %"j", i32 %".1", 1, 0 + """) + else: + self.check_block(block, """\ + my_block: + %"c" = extractvalue {i32, i1} {i32 4, i1 true}, 0 + %"d" = insertvalue {i32, i1} {i32 4, i1 true}, i32 %".1", 0 + %"e" = insertvalue {i32, i1} %"d", i1 false, 1 + %"ptr" = alloca {i8, {i32, i1}} + %"j" = load {i8, {i32, i1}}, {i8, {i32, i1}}* %"ptr" + %"k" = extractvalue {i8, {i32, i1}} %"j", 0 + %"l" = extractvalue {i8, {i32, i1}} %"j", 1 + %"m" = extractvalue {i8, {i32, i1}} %"j", 1, 0 + %"n" = extractvalue {i8, {i32, i1}} %"j", 1, 1 + %"o" = insertvalue {i8, {i32, i1}} %"j", {i32, i1} %"l", 1 + %"p" = insertvalue {i8, {i32, i1}} %"j", i32 %".1", 1, 0 + """) + + def test_cast_ops(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b, fa, ptr = builder.function.args[:4] + c = builder.trunc(a, int8, name='c') + d = builder.zext(c, int32, name='d') # noqa F841 + e = builder.sext(c, int32, name='e') # noqa F841 + fb = builder.fptrunc(fa, flt, 'fb') + fc = builder.fpext(fb, dbl, 'fc') # noqa F841 + g = builder.fptoui(fa, int32, 'g') + h = builder.fptosi(fa, int8, 'h') + fd = builder.uitofp(g, flt, 'fd') # noqa F841 + fe = builder.sitofp(h, dbl, 'fe') # noqa F841 + i = builder.ptrtoint(ptr, int32, 'i') + j = builder.inttoptr(i, ir.PointerType(int8), 'j') # noqa F841 + k = builder.bitcast(a, flt, "k") # noqa F841 + self.assertFalse(block.is_terminated) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = trunc i32 %".1" to i8 + %"d" = zext i8 %"c" to i32 + %"e" = sext i8 %"c" to i32 + %"fb" = fptrunc double %".3" to float + %"fc" = fpext float %"fb" to double + %"g" = fptoui double %".3" to i32 + %"h" = fptosi double %".3" to i8 + %"fd" = uitofp i32 %"g" to float + %"fe" = sitofp i8 %"h" to double + %"i" = ptrtoint ptr %".4" to i32 + %"j" = inttoptr i32 %"i" to ptr + %"k" = bitcast i32 %".1" to float + """) + else: + self.check_block(block, """\ + my_block: + %"c" = trunc i32 %".1" to i8 + %"d" = zext i8 %"c" to i32 + %"e" = sext i8 %"c" to i32 + %"fb" = fptrunc double %".3" to float + %"fc" = fpext float %"fb" to double + %"g" = fptoui double %".3" to i32 + %"h" = fptosi double %".3" to i8 + %"fd" = uitofp i32 %"g" to float + %"fe" = sitofp i8 %"h" to double + %"i" = ptrtoint i32* %".4" to i32 + %"j" = inttoptr i32 %"i" to i8* + %"k" = bitcast i32 %".1" to float + """) + + def test_atomicrmw(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.alloca(int32, name='c') + d = builder.atomic_rmw('add', c, a, 'monotonic', 'd') + self.assertEqual(d.type, int32) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = atomicrmw add ptr %"c", i32 %".1" monotonic + """) + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32 + %"d" = atomicrmw add i32* %"c", i32 %".1" monotonic + """) + + def test_branch(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_target = builder.function.append_basic_block(name='target') + builder.branch(bb_target) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + br label %"target" + """) + + def test_cbranch(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_true = builder.function.append_basic_block(name='b_true') + bb_false = builder.function.append_basic_block(name='b_false') + builder.cbranch(ir.Constant(int1, False), bb_true, bb_false) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + br i1 false, label %"b_true", label %"b_false" + """) + + def test_cbranch_weights(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_true = builder.function.append_basic_block(name='b_true') + bb_false = builder.function.append_basic_block(name='b_false') + br = builder.cbranch(ir.Constant(int1, False), bb_true, bb_false) + br.set_weights([5, 42]) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + br i1 false, label %"b_true", label %"b_false", !prof !0 + """) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 5, i32 42 } + """) + + def test_branch_indirect(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + bb_1 = builder.function.append_basic_block(name='b_1') + bb_2 = builder.function.append_basic_block(name='b_2') + indirectbr = builder.branch_indirect( + ir.BlockAddress(builder.function, bb_1)) + indirectbr.add_destination(bb_1) + indirectbr.add_destination(bb_2) + self.assertTrue(block.is_terminated) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + indirectbr ptr blockaddress(@"my_func", %"b_1"), [label %"b_1", label %"b_2"] + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + indirectbr i8* blockaddress(@"my_func", %"b_1"), [label %"b_1", label %"b_2"] + """) # noqa E501 + + def test_returns(self): + def check(block, expected_ir): + self.assertTrue(block.is_terminated) + self.check_block(block, expected_ir) + + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + builder.ret_void() + check(block, """\ + my_block: + ret void + """) + + block = self.block(name='other_block') + builder = ir.IRBuilder(block) + builder.ret(int32(5)) + check(block, """\ + other_block: + ret i32 5 + """) + + # With metadata + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + inst = builder.ret_void() + inst.set_metadata("dbg", block.module.add_metadata(())) + check(block, """\ + my_block: + ret void, !dbg !0 + """) + + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + inst = builder.ret(int32(6)) + inst.set_metadata("dbg", block.module.add_metadata(())) + check(block, """\ + my_block: + ret i32 6, !dbg !0 + """) + + def test_switch(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + bb_onzero = builder.function.append_basic_block(name='onzero') + bb_onone = builder.function.append_basic_block(name='onone') + bb_ontwo = builder.function.append_basic_block(name='ontwo') + bb_else = builder.function.append_basic_block(name='otherwise') + sw = builder.switch(a, bb_else) + sw.add_case(ir.Constant(int32, 0), bb_onzero) + sw.add_case(ir.Constant(int32, 1), bb_onone) + # A plain Python value gets converted into the right IR constant + sw.add_case(2, bb_ontwo) + self.assertTrue(block.is_terminated) + self.check_block(block, """\ + my_block: + switch i32 %".1", label %"otherwise" [i32 0, label %"onzero" i32 1, label %"onone" i32 2, label %"ontwo"] + """) # noqa E501 + + def test_call(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + tp_f = ir.FunctionType(flt, (int32, int32)) + tp_g = ir.FunctionType(dbl, (int32,), var_arg=True) + tp_h = ir.FunctionType(hlf, (int32, int32)) + f = ir.Function(builder.function.module, tp_f, 'f') + g = ir.Function(builder.function.module, tp_g, 'g') + h = ir.Function(builder.function.module, tp_h, 'h') + builder.call(f, (a, b), 'res_f') + builder.call(g, (b, a), 'res_g') + builder.call(h, (a, b), 'res_h') + builder.call(f, (a, b), 'res_f_fast', cconv='fastcc') + res_f_readonly = builder.call(f, (a, b), 'res_f_readonly') + res_f_readonly.attributes.add('readonly') + builder.call(f, (a, b), 'res_fast', fastmath='fast') + builder.call(f, (a, b), 'res_nnan_ninf', fastmath=('nnan', 'ninf')) + builder.call(f, (a, b), 'res_noinline', attrs='noinline') + builder.call(f, (a, b), 'res_alwaysinline', attrs='alwaysinline') + builder.call(f, (a, b), 'res_noinline_ro', attrs=('noinline', + 'readonly')) + builder.call(f, (a, b), 'res_convergent', attrs='convergent') + self.check_block(block, """\ + my_block: + %"res_f" = call float @"f"(i32 %".1", i32 %".2") + %"res_g" = call double (i32, ...) @"g"(i32 %".2", i32 %".1") + %"res_h" = call half @"h"(i32 %".1", i32 %".2") + %"res_f_fast" = call fastcc float @"f"(i32 %".1", i32 %".2") + %"res_f_readonly" = call float @"f"(i32 %".1", i32 %".2") readonly + %"res_fast" = call fast float @"f"(i32 %".1", i32 %".2") + %"res_nnan_ninf" = call ninf nnan float @"f"(i32 %".1", i32 %".2") + %"res_noinline" = call float @"f"(i32 %".1", i32 %".2") noinline + %"res_alwaysinline" = call float @"f"(i32 %".1", i32 %".2") alwaysinline + %"res_noinline_ro" = call float @"f"(i32 %".1", i32 %".2") noinline readonly + %"res_convergent" = call float @"f"(i32 %".1", i32 %".2") convergent + """) # noqa E501 + + def test_call_metadata(self): + """ + Function calls with metadata arguments. + """ + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + dbg_declare_ty = ir.FunctionType(ir.VoidType(), [ir.MetaDataType()] * 3) + dbg_declare = ir.Function( + builder.module, + dbg_declare_ty, + 'llvm.dbg.declare') + a = builder.alloca(int32, name="a") + b = builder.module.add_metadata(()) + builder.call(dbg_declare, (a, b, b)) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"a" = alloca i32 + call void @"llvm.dbg.declare"(metadata ptr %"a", metadata !0, metadata !0) + """) # noqa E501 + else: + self.check_block(block, """\ + my_block: + %"a" = alloca i32 + call void @"llvm.dbg.declare"(metadata i32* %"a", metadata !0, metadata !0) + """) # noqa E501 + + def test_call_attributes(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType( + ir.VoidType(), (int32.as_pointer(), int32, int32.as_pointer())) + fun = ir.Function(builder.function.module, fun_ty, 'fun') + fun.args[0].add_attribute('sret') + retval = builder.alloca(int32, name='retval') + other = builder.alloca(int32, name='other') + builder.call( + fun, + (retval, ir.Constant(int32, 42), other), + arg_attrs={ + 0: ('sret', 'noalias'), + 2: 'noalias' + } + ) + if not ir_layer_typed_pointers_enabled: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + call void @"fun"\\(ptr noalias sret(\\(i32\\))? %"retval", i32 42, ptr noalias %"other"\\) + """) # noqa E501 + else: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + call void @"fun"\\(i32\\* noalias sret(\\(i32\\))? %"retval", i32 42, i32\\* noalias %"other"\\) + """) # noqa E501 + + def test_call_tail(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType(ir.VoidType(), ()) + fun = ir.Function(builder.function.module, fun_ty, 'my_fun') + + builder.call(fun, ()) + builder.call(fun, (), tail=False) + builder.call(fun, (), tail=True) + builder.call(fun, (), tail='tail') + builder.call(fun, (), tail='notail') + builder.call(fun, (), tail='musttail') + builder.call(fun, (), tail=[]) # This is a falsy value + builder.call(fun, (), tail='not a marker') # This is a truthy value + + self.check_block(block, """\ + my_block: + call void @"my_fun"() + call void @"my_fun"() + tail call void @"my_fun"() + tail call void @"my_fun"() + notail call void @"my_fun"() + musttail call void @"my_fun"() + call void @"my_fun"() + tail call void @"my_fun"() + """) # noqa E501 + + def test_invalid_call_attributes(self): + block = self.block() + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType(ir.VoidType(), ()) + fun = ir.Function(builder.function.module, fun_ty, 'fun') + with self.assertRaises(ValueError): + # The function has no arguments, so this should fail. + builder.call(fun, (), arg_attrs={0: 'sret'}) + + def test_invoke(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + tp_f = ir.FunctionType(flt, (int32, int32)) + f = ir.Function(builder.function.module, tp_f, 'f') + bb_normal = builder.function.append_basic_block(name='normal') + bb_unwind = builder.function.append_basic_block(name='unwind') + builder.invoke(f, (a, b), bb_normal, bb_unwind, 'res_f') + self.check_block(block, """\ + my_block: + %"res_f" = invoke float @"f"(i32 %".1", i32 %".2") + to label %"normal" unwind label %"unwind" + """) + + def test_invoke_attributes(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + fun_ty = ir.FunctionType( + ir.VoidType(), (int32.as_pointer(), int32, int32.as_pointer())) + fun = ir.Function(builder.function.module, fun_ty, 'fun') + fun.calling_convention = "fastcc" + fun.args[0].add_attribute('sret') + retval = builder.alloca(int32, name='retval') + other = builder.alloca(int32, name='other') + bb_normal = builder.function.append_basic_block(name='normal') + bb_unwind = builder.function.append_basic_block(name='unwind') + builder.invoke( + fun, + (retval, ir.Constant(int32, 42), other), + bb_normal, + bb_unwind, + cconv='fastcc', + fastmath='fast', + attrs='noinline', + arg_attrs={ + 0: ('sret', 'noalias'), + 2: 'noalias' + } + ) + if not ir_layer_typed_pointers_enabled: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + invoke fast fastcc void @"fun"\\(ptr noalias sret(\\(i32\\))? %"retval", i32 42, ptr noalias %"other"\\) noinline + to label %"normal" unwind label %"unwind" + """) # noqa E501 + else: + self.check_block_regex(block, """\ + my_block: + %"retval" = alloca i32 + %"other" = alloca i32 + invoke fast fastcc void @"fun"\\(i32\\* noalias sret(\\(i32\\))? %"retval", i32 42, i32\\* noalias %"other"\\) noinline + to label %"normal" unwind label %"unwind" + """) # noqa E501 + + def test_landingpad(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + lp = builder.landingpad(ir.LiteralStructType([int32, + int8.as_pointer()]), 'lp') + int_typeinfo = ir.GlobalVariable(builder.function.module, + int8.as_pointer(), "_ZTIi") + int_typeinfo.global_constant = True + lp.add_clause(ir.CatchClause(int_typeinfo)) + lp.add_clause(ir.FilterClause(ir.Constant(ir.ArrayType( + int_typeinfo.type, 1), [int_typeinfo]))) + builder.resume(lp) + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"lp" = landingpad {i32, ptr} + catch ptr @"_ZTIi" + filter [1 x ptr] [ptr @"_ZTIi"] + resume {i32, ptr} %"lp" + """) + else: + self.check_block(block, """\ + my_block: + %"lp" = landingpad {i32, i8*} + catch i8** @"_ZTIi" + filter [1 x i8**] [i8** @"_ZTIi"] + resume {i32, i8*} %"lp" + """) + + def test_assume(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + c = builder.icmp_signed('>', a, b, name='c') + builder.assume(c) + self.check_block(block, """\ + my_block: + %"c" = icmp sgt i32 %".1", %".2" + call void @"llvm.assume"(i1 %"c") + """) + + def test_vector_ops(self): + block = self.block(name='insert_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + a.name = 'a' + b.name = 'b' + + vecty = ir.VectorType(a.type, 2) + vec = ir.Constant(vecty, ir.Undefined) + idxty = ir.IntType(32) + vec = builder.insert_element(vec, a, idxty(0), name='vec1') + vec = builder.insert_element(vec, b, idxty(1), name='vec2') + + self.check_block(block, """\ +insert_block: + %"vec1" = insertelement <2 x i32> , i32 %"a", i32 0 + %"vec2" = insertelement <2 x i32> %"vec1", i32 %"b", i32 1 + """) + + block = builder.append_basic_block("shuffle_block") + builder.branch(block) + builder.position_at_end(block) + + mask = ir.Constant(vecty, [1, 0]) + builder.shuffle_vector(vec, vec, mask, name='shuf') + + self.check_block(block, """\ + shuffle_block: + %"shuf" = shufflevector <2 x i32> %"vec2", <2 x i32> %"vec2", <2 x i32> + """) # noqa E501 + + block = builder.append_basic_block("add_block") + builder.branch(block) + builder.position_at_end(block) + + builder.add(vec, vec, name='sum') + + self.check_block(block, """\ + add_block: + %"sum" = add <2 x i32> %"vec2", %"vec2" + """) + + block = builder.append_basic_block("extract_block") + builder.branch(block) + builder.position_at_end(block) + + c = builder.extract_element(vec, idxty(0), name='ex1') + d = builder.extract_element(vec, idxty(1), name='ex2') + + self.check_block(block, """\ + extract_block: + %"ex1" = extractelement <2 x i32> %"vec2", i32 0 + %"ex2" = extractelement <2 x i32> %"vec2", i32 1 + """) + + builder.ret(builder.add(c, d)) + self.assert_valid_ir(builder.module) + + def test_bitreverse(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int64, 5) + c = builder.bitreverse(a, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i64 @"llvm.bitreverse.i64"(i64 5) + ret i64 %"c" + """) + + def test_bitreverse_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + + with self.assertRaises(TypeError) as raises: + builder.bitreverse(a, name='c') + self.assertIn( + "expected an integer type, got float", + str(raises.exception)) + + def test_fence(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + with self.assertRaises(ValueError) as raises: + builder.fence("monotonic", None) + self.assertIn( + "Invalid fence ordering \"monotonic\"!", + str(raises.exception)) + with self.assertRaises(ValueError) as raises: + builder.fence(None, "monotonic") + self.assertIn( + "Invalid fence ordering \"None\"!", + str(raises.exception)) + builder.fence("acquire", None) + builder.fence("release", "singlethread") + builder.fence("acq_rel", "singlethread") + builder.fence("seq_cst") + builder.ret_void() + self.check_block(block, """\ + my_block: + fence acquire + fence syncscope("singlethread") release + fence syncscope("singlethread") acq_rel + fence seq_cst + ret void + """) + + def test_comment(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + with self.assertRaises(AssertionError): + builder.comment("so\nmany lines") + builder.comment("my comment") + builder.ret_void() + self.check_block(block, """\ + my_block: + ; my comment + ret void + """) + + def test_bswap(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int32, 5) + c = builder.bswap(a, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i32 @"llvm.bswap.i32"(i32 5) + ret i32 %"c" + """) + + def test_ctpop(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + c = builder.ctpop(a, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i16 @"llvm.ctpop.i16"(i16 5) + ret i16 %"c" + """) + + def test_ctlz(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + b = ir.Constant(int1, 1) + c = builder.ctlz(a, b, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i16 @"llvm.ctlz.i16"(i16 5, i1 1) + ret i16 %"c" + """) + + def test_convert_to_fp16_f32(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.0) + b = builder.convert_to_fp16(a, name='b') + builder.ret(b) + self.check_block(block, """\ + my_block: + %"b" = call i16 @"llvm.convert.to.fp16.f32"(float 0x4014000000000000) + ret i16 %"b" + """) # noqa E501 + + def test_convert_to_fp16_f32_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + + with self.assertRaises(TypeError) as raises: + builder.convert_to_fp16(a, name='b') + self.assertIn( + "expected a float type, got i16", + str(raises.exception)) + + def test_convert_from_fp16_f32(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int16, 5) + b = builder.convert_from_fp16(a, name='b', to=flt) + builder.ret(b) + self.check_block(block, """\ + my_block: + %"b" = call float @"llvm.convert.from.fp16.f32"(i16 5) + ret float %"b" + """) + + def test_convert_from_fp16_f32_notype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.5) + + with self.assertRaises(TypeError) as raises: + builder.convert_from_fp16(a, name='b') + self.assertIn( + "expected a float return type", + str(raises.exception)) + + def test_convert_from_fp16_f32_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.5) + + with self.assertRaises(TypeError) as raises: + builder.convert_from_fp16(a, name='b', to=flt) + self.assertIn( + "expected an i16 type, got float", + str(raises.exception)) + + def test_convert_from_fp16_f32_wrongtype2(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5.5) + + with self.assertRaises(TypeError) as raises: + builder.convert_from_fp16(a, name='b', to=int16) + self.assertIn( + "expected a float type, got i16", + str(raises.exception)) + + def test_cttz(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int64, 5) + b = ir.Constant(int1, 1) + c = builder.cttz(a, b, name='c') + builder.ret(c) + self.check_block(block, """\ + my_block: + %"c" = call i64 @"llvm.cttz.i64"(i64 5, i1 1) + ret i64 %"c" + """) + + def test_cttz_wrongflag(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int64, 5) + b = ir.Constant(int32, 3) + + with self.assertRaises(TypeError) as raises: + builder.cttz(a, b, name='c') + self.assertIn( + "expected an i1 type, got i32", + str(raises.exception)) + + def test_cttz_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + b = ir.Constant(int1, 1) + + with self.assertRaises(TypeError) as raises: + builder.cttz(a, b, name='c') + self.assertIn( + "expected an integer type, got float", + str(raises.exception)) + + def test_fma(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + b = ir.Constant(flt, 1) + c = ir.Constant(flt, 2) + fma = builder.fma(a, b, c, name='fma') + builder.ret(fma) + self.check_block(block, """\ + my_block: + %"fma" = call float @"llvm.fma.f32"(float 0x4014000000000000, float 0x3ff0000000000000, float 0x4000000000000000) + ret float %"fma" + """) # noqa E501 + + def test_fma_wrongtype(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(int32, 5) + b = ir.Constant(int32, 1) + c = ir.Constant(int32, 2) + + with self.assertRaises(TypeError) as raises: + builder.fma(a, b, c, name='fma') + self.assertIn( + "expected an floating point type, got i32", + str(raises.exception)) + + def test_fma_mixedtypes(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a = ir.Constant(flt, 5) + b = ir.Constant(dbl, 1) + c = ir.Constant(flt, 2) + + with self.assertRaises(TypeError) as raises: + builder.fma(a, b, c, name='fma') + self.assertIn( + "expected types to be the same, got float, double, float", + str(raises.exception)) + + def test_arg_attributes(self): + def gen_code(attr_name): + fnty = ir.FunctionType(ir.IntType(32), [ir.IntType(32).as_pointer(), + ir.IntType(32)]) + module = ir.Module() + + func = ir.Function(module, fnty, name="sum") + + bb_entry = func.append_basic_block() + bb_loop = func.append_basic_block() + bb_exit = func.append_basic_block() + + builder = ir.IRBuilder() + builder.position_at_end(bb_entry) + + builder.branch(bb_loop) + builder.position_at_end(bb_loop) + + index = builder.phi(ir.IntType(32)) + index.add_incoming(ir.Constant(index.type, 0), bb_entry) + accum = builder.phi(ir.IntType(32)) + accum.add_incoming(ir.Constant(accum.type, 0), bb_entry) + + func.args[0].add_attribute(attr_name) + ptr = builder.gep(func.args[0], [index]) + value = builder.load(ptr) + + added = builder.add(accum, value) + accum.add_incoming(added, bb_loop) + + indexp1 = builder.add(index, ir.Constant(index.type, 1)) + index.add_incoming(indexp1, bb_loop) + + cond = builder.icmp_unsigned('<', indexp1, func.args[1]) + builder.cbranch(cond, bb_loop, bb_exit) + + builder.position_at_end(bb_exit) + builder.ret(added) + + return str(module) + + for attr_name in ( + 'byref', + 'byval', + 'elementtype', + 'immarg', + 'inalloca', + 'inreg', + 'nest', + 'noalias', + 'nocapture', + 'nofree', + 'nonnull', + 'noundef', + 'preallocated', + 'returned', + 'signext', + 'swiftasync', + 'swifterror', + 'swiftself', + 'zeroext', + ): + # If this parses, we emitted the right byval attribute format + llvm.parse_assembly(gen_code(attr_name)) + # sret doesn't fit this pattern and is tested in test_call_attributes + + +class TestBuilderMisc(TestBase): + """ + Test various other features of the IRBuilder class. + """ + + def test_attributes(self): + block = self.block(name='start') + builder = ir.IRBuilder(block) + self.assertIs(builder.function, block.parent) + self.assertIsInstance(builder.function, ir.Function) + self.assertIs(builder.module, block.parent.module) + self.assertIsInstance(builder.module, ir.Module) + + def test_goto_block(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + a, b = builder.function.args[:2] + builder.add(a, b, 'c') + bb_new = builder.append_basic_block(name='foo') + with builder.goto_block(bb_new): + builder.fadd(a, b, 'd') + with builder.goto_entry_block(): + builder.sub(a, b, 'e') + builder.fsub(a, b, 'f') + builder.branch(bb_new) + builder.mul(a, b, 'g') + with builder.goto_block(bb_new): + builder.fmul(a, b, 'h') + self.check_block(block, """\ + my_block: + %"c" = add i32 %".1", %".2" + %"e" = sub i32 %".1", %".2" + %"g" = mul i32 %".1", %".2" + """) + self.check_block(bb_new, """\ + foo: + %"d" = fadd i32 %".1", %".2" + %"f" = fsub i32 %".1", %".2" + %"h" = fmul i32 %".1", %".2" + br label %"foo" + """) + + def test_if_then(self): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_then(a) as bbend: + builder.add(z, z, 'b') + # Block will be terminated implicitly + self.assertIs(builder.block, bbend) + c = builder.add(z, z, 'c') + with builder.if_then(c): + builder.add(z, z, 'd') + builder.branch(block) + # No implicit termination + self.check_func_body(builder.function, """\ + one: + %"a" = add i1 0, 0 + br i1 %"a", label %"one.if", label %"one.endif" + one.if: + %"b" = add i1 0, 0 + br label %"one.endif" + one.endif: + %"c" = add i1 0, 0 + br i1 %"c", label %"one.endif.if", label %"one.endif.endif" + one.endif.if: + %"d" = add i1 0, 0 + br label %"one" + one.endif.endif: + """) + + def test_if_then_nested(self): + # Implicit termination in a nested if/then + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_then(a): + b = builder.add(z, z, 'b') + with builder.if_then(b): + builder.add(z, z, 'c') + builder.ret_void() + self.check_func_body(builder.function, """\ + one: + %"a" = add i1 0, 0 + br i1 %"a", label %"one.if", label %"one.endif" + one.if: + %"b" = add i1 0, 0 + br i1 %"b", label %"one.if.if", label %"one.if.endif" + one.endif: + ret void + one.if.if: + %"c" = add i1 0, 0 + br label %"one.if.endif" + one.if.endif: + br label %"one.endif" + """) + + def test_if_then_long_label(self): + full_label = 'Long' * 20 + block = self.block(name=full_label) + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_then(a): + b = builder.add(z, z, 'b') + with builder.if_then(b): + builder.add(z, z, 'c') + builder.ret_void() + self.check_func_body(builder.function, """\ + {full_label}: + %"a" = add i1 0, 0 + br i1 %"a", label %"{label}.if", label %"{label}.endif" + {label}.if: + %"b" = add i1 0, 0 + br i1 %"b", label %"{label}.if.if", label %"{label}.if.endif" + {label}.endif: + ret void + {label}.if.if: + %"c" = add i1 0, 0 + br label %"{label}.if.endif" + {label}.if.endif: + br label %"{label}.endif" + """.format(full_label=full_label, label=full_label[:25] + '..')) + + def test_if_then_likely(self): + def check(likely): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + with builder.if_then(z, likely=likely): + pass + self.check_block(block, """\ + one: + br i1 0, label %"one.if", label %"one.endif", !prof !0 + """) + return builder + builder = check(True) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 99, i32 1 } + """) + builder = check(False) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 1, i32 99 } + """) + + def test_if_else(self): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + a = builder.add(z, z, 'a') + with builder.if_else(a) as (then, otherwise): + with then: + builder.add(z, z, 'b') + with otherwise: + builder.add(z, z, 'c') + # Each block will be terminated implicitly + with builder.if_else(a) as (then, otherwise): + with then: + builder.branch(block) + with otherwise: + builder.ret_void() + # No implicit termination + self.check_func_body(builder.function, """\ + one: + %"a" = add i1 0, 0 + br i1 %"a", label %"one.if", label %"one.else" + one.if: + %"b" = add i1 0, 0 + br label %"one.endif" + one.else: + %"c" = add i1 0, 0 + br label %"one.endif" + one.endif: + br i1 %"a", label %"one.endif.if", label %"one.endif.else" + one.endif.if: + br label %"one" + one.endif.else: + ret void + one.endif.endif: + """) + + def test_if_else_likely(self): + def check(likely): + block = self.block(name='one') + builder = ir.IRBuilder(block) + z = ir.Constant(int1, 0) + with builder.if_else(z, likely=likely) as (then, otherwise): + with then: + builder.branch(block) + with otherwise: + builder.ret_void() + self.check_func_body(builder.function, """\ + one: + br i1 0, label %"one.if", label %"one.else", !prof !0 + one.if: + br label %"one" + one.else: + ret void + one.endif: + """) + return builder + builder = check(True) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 99, i32 1 } + """) + builder = check(False) + self.check_metadata(builder.module, """\ + !0 = !{ !"branch_weights", i32 1, i32 99 } + """) + + def test_positioning(self): + """ + Test IRBuilder.position_{before,after,at_start,at_end}. + """ + func = self.function() + builder = ir.IRBuilder() + z = ir.Constant(int32, 0) + bb_one = func.append_basic_block(name='one') + bb_two = func.append_basic_block(name='two') + bb_three = func.append_basic_block(name='three') + # .at_start(empty block) + builder.position_at_start(bb_one) + builder.add(z, z, 'a') + # .at_end(empty block) + builder.position_at_end(bb_two) + builder.add(z, z, 'm') + builder.add(z, z, 'n') + # .at_start(block) + builder.position_at_start(bb_two) + o = builder.add(z, z, 'o') + builder.add(z, z, 'p') + # .at_end(block) + builder.position_at_end(bb_one) + b = builder.add(z, z, 'b') + # .after(instr) + builder.position_after(o) + builder.add(z, z, 'q') + # .before(instr) + builder.position_before(b) + builder.add(z, z, 'c') + self.check_block(bb_one, """\ + one: + %"a" = add i32 0, 0 + %"c" = add i32 0, 0 + %"b" = add i32 0, 0 + """) + self.check_block(bb_two, """\ + two: + %"o" = add i32 0, 0 + %"q" = add i32 0, 0 + %"p" = add i32 0, 0 + %"m" = add i32 0, 0 + %"n" = add i32 0, 0 + """) + self.check_block(bb_three, """\ + three: + """) + + def test_instruction_removal(self): + func = self.function() + builder = ir.IRBuilder() + blk = func.append_basic_block(name='entry') + builder.position_at_end(blk) + k = ir.Constant(int32, 1234) + a = builder.add(k, k, 'a') + retvoid = builder.ret_void() + self.assertTrue(blk.is_terminated) + builder.remove(retvoid) + self.assertFalse(blk.is_terminated) + b = builder.mul(a, a, 'b') + c = builder.add(b, b, 'c') + builder.remove(c) + builder.ret_void() + self.assertTrue(blk.is_terminated) + self.check_block(blk, """\ + entry: + %"a" = add i32 1234, 1234 + %"b" = mul i32 %"a", %"a" + ret void + """) + + def test_metadata(self): + block = self.block(name='my_block') + builder = ir.IRBuilder(block) + builder.debug_metadata = builder.module.add_metadata([]) + builder.alloca(ir.PointerType(int32), name='c') + if not ir_layer_typed_pointers_enabled: + self.check_block(block, """\ + my_block: + %"c" = alloca ptr, !dbg !0 + """) + else: + self.check_block(block, """\ + my_block: + %"c" = alloca i32*, !dbg !0 + """) + + +class TestTypes(TestBase): + + def has_logical_equality(self, ty): + while isinstance(ty, ir.PointerType): + ty = ty.pointee + return not isinstance(ty, ir.LabelType) + + def assorted_types(self): + """ + A bunch of mutually unequal types + """ + # Avoid polluting the namespace + context = ir.Context() + types = [ + ir.LabelType(), ir.VoidType(), + ir.FunctionType(int1, (int8, int8)), ir.FunctionType(int1, (int8,)), + ir.FunctionType(int1, (int8,), var_arg=True), + ir.FunctionType(int8, (int8,)), + int1, int8, int32, flt, dbl, + ir.ArrayType(flt, 5), ir.ArrayType(dbl, 5), ir.ArrayType(dbl, 4), + ir.LiteralStructType((int1, int8)), ir.LiteralStructType((int8, + int1)), + context.get_identified_type("MyType1"), + context.get_identified_type("MyType2"), + ] + types += [ir.PointerType(tp) for tp in types + if not isinstance(tp, (ir.VoidType, ir.LabelType))] + + return types + + def test_pickling(self): + types = self.assorted_types() + for ty in types: + newty = self.assert_pickle_correctly(ty) + if self.has_logical_equality(ty): + self.assertEqual(newty, ty) + + def test_comparisons(self): + types = self.assorted_types() + for a, b in itertools.product(types, types): + if a is not b: + self.assertFalse(a == b, (a, b)) + self.assertTrue(a != b, (a, b)) + # We assume copy.copy() works fine here... + for tp in types: + other = copy.copy(tp) + if self.has_logical_equality(tp): + self.assertTrue(tp == other, (tp, other)) + self.assertFalse(tp != other, (tp, other)) + else: + self.assertFalse(tp == other, (tp, other)) + self.assertTrue(tp != other, (tp, other)) + + def test_ptr_comparisons(self): + # Create instances of: + # * Opaque pointers. + # * Typed pointers of i1's. + # * Typed pointers of i8's. + # The choice of types for the typed pointers are not consequential - + # they just need to differ. Each pointer class has two instances, one + # in address space 0, another in address space 1. + ptrs = { + 'op_a0': ir.PointerType(), + 'op_a1': ir.PointerType(addrspace=1), + 'tp_i1_a0': ir.PointerType(int1), + 'tp_i1_a1': ir.PointerType(int1, addrspace=1), + 'tp_i8_a0': ir.PointerType(int8), + 'tp_i8_a1': ir.PointerType(int8, addrspace=1), + } + + def assert_eq(ptr1, ptr2): + self.assertTrue(ptr1 == ptr2, (ptr1, ptr2)) + self.assertTrue(ptr2 == ptr1, (ptr2, ptr1)) + + self.assertFalse(ptr1 != ptr2, (ptr1, ptr2)) + self.assertFalse(ptr2 != ptr1, (ptr2, ptr1)) + + def assert_ne(ptr1, ptr2): + self.assertFalse(ptr1 == ptr2, (ptr1, ptr2)) + self.assertFalse(ptr2 == ptr1, (ptr2, ptr1)) + + self.assertTrue(ptr1 != ptr2, (ptr1, ptr2)) + self.assertTrue(ptr2 != ptr1, (ptr2, ptr1)) + + for ptr in ptrs.values(): + # Compare the pointers against any non-pointer type. + for other in self.assorted_types(): + if not isinstance(other, ir.PointerType): + assert_ne(ptr, other) + # Compare the pointers against themselves. + assert_eq(ptr, ptr) + + # Compare the pointers against each other. + # Opaque pointers are always equal, unless their address space differs. + # Typed pointers always differ, unless their pointee type and address + # space match. + assert_ne(ptrs['op_a0'], ptrs['op_a1']) + assert_eq(ptrs['op_a0'], ptrs['tp_i1_a0']) + assert_ne(ptrs['op_a0'], ptrs['tp_i1_a1']) + assert_eq(ptrs['op_a0'], ptrs['tp_i8_a0']) + assert_ne(ptrs['op_a0'], ptrs['tp_i8_a1']) + assert_ne(ptrs['op_a1'], ptrs['tp_i1_a0']) + assert_eq(ptrs['op_a1'], ptrs['tp_i1_a1']) + assert_ne(ptrs['op_a1'], ptrs['tp_i8_a0']) + assert_eq(ptrs['op_a1'], ptrs['tp_i8_a1']) + assert_ne(ptrs['tp_i1_a0'], ptrs['tp_i1_a1']) + assert_ne(ptrs['tp_i1_a0'], ptrs['tp_i8_a0']) + assert_ne(ptrs['tp_i1_a0'], ptrs['tp_i8_a1']) + assert_ne(ptrs['tp_i1_a1'], ptrs['tp_i8_a0']) + assert_ne(ptrs['tp_i1_a1'], ptrs['tp_i8_a1']) + assert_ne(ptrs['tp_i8_a0'], ptrs['tp_i8_a1']) + + def test_pointers(self): + # Basic opaque pointers. + ptr = ir.PointerType() + ptr2 = ir.PointerType(addrspace=2) + + self.assertTrue(ptr.is_opaque) + self.assertTrue(ptr2.is_opaque) + + self.assertEqual(str(ptr), "ptr") + self.assertEqual(str(ptr2), "ptr addrspace(2)") + + # Pointers of opaque pointers (necessarily opaque pointers). + ptr_ptr = ptr.as_pointer() + ptr2_ptr = ptr2.as_pointer() + ptr2_ptr3 = ptr2.as_pointer(addrspace=3) + + self.assertTrue(ptr_ptr.is_opaque) + self.assertTrue(ptr2_ptr.is_opaque) + self.assertTrue(ptr2_ptr3.is_opaque) + + self.assertEqual(str(ptr_ptr), "ptr") + self.assertEqual(str(ptr2_ptr), "ptr") + self.assertEqual(str(ptr2_ptr3), "ptr addrspace(3)") + + # Basic typed pointers. + tptr = ir.IntType(32).as_pointer() + tptr2 = ir.IntType(32).as_pointer(addrspace=2) + + self.assertTrue(not tptr.is_opaque) + self.assertTrue(not tptr2.is_opaque) + + if ir_layer_typed_pointers_enabled: + self.assertEqual(str(tptr), "i32*") + self.assertEqual(str(tptr2), "i32 addrspace(2)*") + else: + self.assertEqual(str(tptr), "ptr") + self.assertEqual(str(tptr2), "ptr addrspace(2)") + + # Pointers of typed pointers (necessarily typed pointers). + tptr_ptr = tptr.as_pointer() + tptr2_ptr = tptr2.as_pointer() + tptr2_ptr3 = tptr2.as_pointer(addrspace=3) + + self.assertTrue(not tptr_ptr.is_opaque) + self.assertTrue(not tptr2_ptr.is_opaque) + self.assertTrue(not tptr2_ptr3.is_opaque) + + if ir_layer_typed_pointers_enabled: + self.assertEqual(str(tptr_ptr), "i32**") + self.assertEqual(str(tptr2_ptr), "i32 addrspace(2)**") + self.assertEqual(str(tptr2_ptr3), "i32 addrspace(2)* addrspace(3)*") + else: + self.assertEqual(str(tptr_ptr), "ptr") + self.assertEqual(str(tptr2_ptr), "ptr") + self.assertEqual(str(tptr2_ptr3), "ptr addrspace(3)") + + def test_ptr_intrinsic_name(self): + self.assertEqual(ir.PointerType().intrinsic_name, 'p0') + self.assertEqual(ir.PointerType(addrspace=1).intrinsic_name, 'p1') + if not ir_layer_typed_pointers_enabled: + self.assertEqual(ir.PointerType(int1).intrinsic_name, 'p0') + self.assertEqual(ir.PointerType(int1, 1).intrinsic_name, 'p1') + else: + self.assertEqual(ir.PointerType(int1).intrinsic_name, 'p0i1') + self.assertEqual(ir.PointerType(int1, 1).intrinsic_name, 'p1i1') + + def test_str(self): + """ + Test the string representation of types. + """ + self.assertEqual(str(int1), 'i1') + self.assertEqual(str(ir.IntType(29)), 'i29') + self.assertEqual(str(flt), 'float') + self.assertEqual(str(dbl), 'double') + self.assertEqual(str(ir.VoidType()), 'void') + self.assertEqual(str(ir.FunctionType(int1, ())), 'i1 ()') + self.assertEqual(str(ir.FunctionType(int1, (flt,))), 'i1 (float)') + self.assertEqual(str(ir.FunctionType(int1, (flt, dbl))), + 'i1 (float, double)') + self.assertEqual(str(ir.FunctionType(int1, (), var_arg=True)), + 'i1 (...)') + self.assertEqual(str(ir.FunctionType(int1, (flt,), var_arg=True)), + 'i1 (float, ...)') + self.assertEqual(str(ir.FunctionType(int1, (flt, dbl), var_arg=True)), + 'i1 (float, double, ...)') + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(ir.PointerType(int32)), 'ptr') + self.assertEqual(str(ir.PointerType(ir.PointerType(int32))), 'ptr') + else: + self.assertEqual(str(ir.PointerType(int32)), 'i32*') + self.assertEqual(str(ir.PointerType(ir.PointerType(int32))), + 'i32**') + self.assertEqual(str(ir.ArrayType(int1, 5)), '[5 x i1]') + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(ir.ArrayType(ir.PointerType(int1), 5)), + '[5 x ptr]') + self.assertEqual(str(ir.PointerType(ir.ArrayType(int1, 5))), 'ptr') + else: + self.assertEqual(str(ir.ArrayType(ir.PointerType(int1), 5)), + '[5 x i1*]') + self.assertEqual(str(ir.PointerType(ir.ArrayType(int1, 5))), + '[5 x i1]*') + self.assertEqual(str(ir.LiteralStructType((int1,))), '{i1}') + self.assertEqual(str(ir.LiteralStructType((int1, flt))), '{i1, float}') + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(ir.LiteralStructType(( + ir.PointerType(int1), ir.LiteralStructType((int32, int8))))), + '{ptr, {i32, i8}}') + else: + self.assertEqual(str(ir.LiteralStructType(( + ir.PointerType(int1), ir.LiteralStructType((int32, int8))))), + '{i1*, {i32, i8}}') + self.assertEqual(str(ir.LiteralStructType((int1,), packed=True)), + '<{i1}>') + self.assertEqual(str(ir.LiteralStructType((int1, flt), packed=True)), + '<{i1, float}>') + + # Avoid polluting the namespace + context = ir.Context() + mytype = context.get_identified_type("MyType") + self.assertEqual(str(mytype), "%\"MyType\"") + mytype1 = context.get_identified_type("MyType\\") + self.assertEqual(str(mytype1), "%\"MyType\\5c\"") + mytype2 = context.get_identified_type("MyType\"") + self.assertEqual(str(mytype2), "%\"MyType\\22\"") + + def test_hash(self): + for typ in filter(self.has_logical_equality, self.assorted_types()): + self.assertEqual(hash(typ), hash(copy.copy(typ))) + + def test_gep(self): + def check_constant(tp, i, expected): + actual = tp.gep(ir.Constant(int32, i)) + self.assertEqual(actual, expected) + + def check_index_type(tp): + index = ir.Constant(dbl, 1.0) + with self.assertRaises(TypeError): + tp.gep(index) + + tp = ir.PointerType(dbl) + for i in range(5): + check_constant(tp, i, dbl) + check_index_type(tp) + + tp = ir.ArrayType(int1, 3) + for i in range(3): + check_constant(tp, i, int1) + check_index_type(tp) + + tp = ir.LiteralStructType((dbl, ir.LiteralStructType((int1, int8)))) + check_constant(tp, 0, dbl) + check_constant(tp, 1, ir.LiteralStructType((int1, int8))) + with self.assertRaises(IndexError): + tp.gep(ir.Constant(int32, 2)) + check_index_type(tp) + + context = ir.Context() + tp = ir.IdentifiedStructType(context, "MyType") + tp.set_body(dbl, ir.LiteralStructType((int1, int8))) + check_constant(tp, 0, dbl) + check_constant(tp, 1, ir.LiteralStructType((int1, int8))) + with self.assertRaises(IndexError): + tp.gep(ir.Constant(int32, 2)) + check_index_type(tp) + + def test_abi_size(self): + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + + def check(tp, expected): + self.assertEqual(tp.get_abi_size(td), expected) + check(int8, 1) + check(int32, 4) + check(int64, 8) + check(ir.ArrayType(int8, 5), 5) + check(ir.ArrayType(int32, 5), 20) + check(ir.LiteralStructType((dbl, flt, flt)), 16) + + def test_abi_alignment(self): + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + + def check(tp, expected): + self.assertIn(tp.get_abi_alignment(td), expected) + check(int8, (1, 2, 4)) + check(int32, (4,)) + check(int64, (8,)) + check(ir.ArrayType(int8, 5), (1, 2, 4)) + check(ir.ArrayType(int32, 5), (4,)) + check(ir.LiteralStructType((dbl, flt, flt)), (8,)) + + def test_identified_struct(self): + context = ir.Context() + mytype = context.get_identified_type("MyType") + module = ir.Module(context=context) + self.assertTrue(mytype.is_opaque) + self.assert_valid_ir(module) + oldstr = str(module) + mytype.set_body(ir.IntType(32), ir.IntType(64), ir.FloatType()) + self.assertFalse(mytype.is_opaque) + self.assert_valid_ir(module) + self.assertNotEqual(oldstr, str(module)) + + def test_identified_struct_packed(self): + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + context = ir.Context() + mytype = context.get_identified_type("MyType", True) + module = ir.Module(context=context) + self.assertTrue(mytype.is_opaque) + self.assert_valid_ir(module) + oldstr = str(module) + mytype.set_body(ir.IntType(16), ir.IntType(64), ir.FloatType()) + self.assertEqual(mytype.get_element_offset(td, 1, context), 2) + self.assertFalse(mytype.is_opaque) + self.assert_valid_ir(module) + self.assertNotEqual(oldstr, str(module)) + + def test_target_data_non_default_context(self): + context = ir.Context() + mytype = context.get_identified_type("MyType") + mytype.elements = [ir.IntType(32)] + td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + self.assertEqual(mytype.get_abi_size(td, context=context), 4) + + def test_vector(self): + vecty = ir.VectorType(ir.IntType(32), 8) + self.assertEqual(str(vecty), "<8 x i32>") + + +def c32(i): + return ir.Constant(int32, i) + + +class TestConstant(TestBase): + + def test_integers(self): + c = ir.Constant(int32, 42) + self.assertEqual(str(c), 'i32 42') + c = ir.Constant(int1, 1) + self.assertEqual(str(c), 'i1 1') + c = ir.Constant(int1, 0) + self.assertEqual(str(c), 'i1 0') + c = ir.Constant(int1, True) + self.assertEqual(str(c), 'i1 true') + c = ir.Constant(int1, False) + self.assertEqual(str(c), 'i1 false') + c = ir.Constant(int1, ir.Undefined) + self.assertEqual(str(c), 'i1 undef') + c = ir.Constant(int1, None) + self.assertEqual(str(c), 'i1 0') + + def test_reals(self): + # XXX Test NaNs and infs + c = ir.Constant(flt, 1.5) + self.assertEqual(str(c), 'float 0x3ff8000000000000') + c = ir.Constant(flt, -1.5) + self.assertEqual(str(c), 'float 0xbff8000000000000') + c = ir.Constant(dbl, 1.5) + self.assertEqual(str(c), 'double 0x3ff8000000000000') + c = ir.Constant(dbl, -1.5) + self.assertEqual(str(c), 'double 0xbff8000000000000') + c = ir.Constant(dbl, ir.Undefined) + self.assertEqual(str(c), 'double undef') + c = ir.Constant(dbl, None) + self.assertEqual(str(c), 'double 0.0') + + def test_arrays(self): + c = ir.Constant(ir.ArrayType(int32, 3), (c32(5), c32(6), c32(4))) + self.assertEqual(str(c), '[3 x i32] [i32 5, i32 6, i32 4]') + c = ir.Constant(ir.ArrayType(int32, 2), (c32(5), c32(ir.Undefined))) + self.assertEqual(str(c), '[2 x i32] [i32 5, i32 undef]') + + c = ir.Constant.literal_array((c32(5), c32(6), c32(ir.Undefined))) + self.assertEqual(str(c), '[3 x i32] [i32 5, i32 6, i32 undef]') + with self.assertRaises(TypeError) as raises: + ir.Constant.literal_array((c32(5), ir.Constant(flt, 1.5))) + self.assertEqual(str(raises.exception), + "all elements must have the same type") + + c = ir.Constant(ir.ArrayType(int32, 2), ir.Undefined) + self.assertEqual(str(c), '[2 x i32] undef') + c = ir.Constant(ir.ArrayType(int32, 2), None) + self.assertEqual(str(c), '[2 x i32] zeroinitializer') + # Raw array syntax + c = ir.Constant(ir.ArrayType(int8, 11), bytearray(b"foobar_123\x80")) + self.assertEqual(str(c), r'[11 x i8] c"foobar_123\80"') + c = ir.Constant(ir.ArrayType(int8, 4), bytearray(b"\x00\x01\x04\xff")) + self.assertEqual(str(c), r'[4 x i8] c"\00\01\04\ff"') + # Recursive instantiation of inner constants + c = ir.Constant(ir.ArrayType(int32, 3), (5, ir.Undefined, 6)) + self.assertEqual(str(c), '[3 x i32] [i32 5, i32 undef, i32 6]') + # Invalid number of args + with self.assertRaises(ValueError): + ir.Constant(ir.ArrayType(int32, 3), (5, 6)) + + def test_vector(self): + vecty = ir.VectorType(ir.IntType(32), 8) + vals = [1, 2, 4, 3, 8, 6, 9, 7] + vec = ir.Constant(vecty, vals) + vec_repr = "<8 x i32> <{}>".format( + ', '.join(map('i32 {}'.format, vals))) + self.assertEqual(str(vec), vec_repr) + + def test_non_nullable_int(self): + constant = ir.Constant(ir.IntType(32), None).constant + self.assertEqual(constant, 0) + + def test_structs(self): + st1 = ir.LiteralStructType((flt, int1)) + st2 = ir.LiteralStructType((int32, st1)) + c = ir.Constant(st1, (ir.Constant(ir.FloatType(), 1.5), + ir.Constant(int1, True))) + self.assertEqual(str(c), + '{float, i1} {float 0x3ff8000000000000, i1 true}') + c = ir.Constant.literal_struct((ir.Constant(ir.FloatType(), 1.5), + ir.Constant(int1, True))) + self.assertEqual(c.type, st1) + self.assertEqual(str(c), + '{float, i1} {float 0x3ff8000000000000, i1 true}') + c = ir.Constant.literal_struct((ir.Constant(ir.FloatType(), 1.5), + ir.Constant(int1, ir.Undefined))) + self.assertEqual(c.type, st1) + self.assertEqual(str(c), + '{float, i1} {float 0x3ff8000000000000, i1 undef}') + c = ir.Constant(st1, ir.Undefined) + self.assertEqual(str(c), '{float, i1} undef') + c = ir.Constant(st1, None) + self.assertEqual(str(c), '{float, i1} zeroinitializer') + # Recursive instantiation of inner constants + c1 = ir.Constant(st1, (1.5, True)) + self.assertEqual(str(c1), + '{float, i1} {float 0x3ff8000000000000, i1 true}') + c2 = ir.Constant(st2, (42, c1)) + self.assertEqual(str(c2), ('{i32, {float, i1}} {i32 42, {float, i1} ' + '{float 0x3ff8000000000000, i1 true}}')) + c3 = ir.Constant(st2, (42, (1.5, True))) + self.assertEqual(str(c3), str(c2)) + # Invalid number of args + with self.assertRaises(ValueError): + ir.Constant(st2, (4, 5, 6)) + + def test_undefined_literal_struct_pickling(self): + i8 = ir.IntType(8) + st = ir.Constant(ir.LiteralStructType([i8, i8]), ir.Undefined) + self.assert_pickle_correctly(st) + + def test_type_instantiaton(self): + """ + Instantiating a type should create a constant. + """ + c = int8(42) + self.assertIsInstance(c, ir.Constant) + self.assertEqual(str(c), 'i8 42') + c = int1(True) + self.assertIsInstance(c, ir.Constant) + self.assertEqual(str(c), 'i1 true') + # Arrays + at = ir.ArrayType(int32, 3) + c = at([c32(4), c32(5), c32(6)]) + self.assertEqual(str(c), '[3 x i32] [i32 4, i32 5, i32 6]') + c = at([4, 5, 6]) + self.assertEqual(str(c), '[3 x i32] [i32 4, i32 5, i32 6]') + c = at(None) + self.assertEqual(str(c), '[3 x i32] zeroinitializer') + with self.assertRaises(ValueError): + at([4, 5, 6, 7]) + # Structs + st1 = ir.LiteralStructType((flt, int1)) + st2 = ir.LiteralStructType((int32, st1)) + c = st1((1.5, True)) + self.assertEqual(str(c), ('{float, i1} {float 0x3ff8000000000000, i1 ' + 'true}')) + c = st2((42, (1.5, True))) + self.assertEqual(str(c), ('{i32, {float, i1}} {i32 42, {float, i1} ' + '{float 0x3ff8000000000000, i1 true}}')) + + def test_repr(self): + """ + Constants should have a useful repr(). + """ + c = int32(42) + self.assertEqual(repr(c), "") + + def test_encoding_problem(self): + c = ir.Constant(ir.ArrayType(ir.IntType(8), 256), + bytearray(range(256))) + m = self.module() + gv = ir.GlobalVariable(m, c.type, "myconstant") + gv.global_constant = True + gv.initializer = c + # With utf-8, the following will cause: + # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position + # 136: invalid continuation byte + parsed = llvm.parse_assembly(str(m)) + # Make sure the encoding does not modify the IR + reparsed = llvm.parse_assembly(str(parsed)) + self.assertEqual(str(parsed), str(reparsed)) + + def test_gep(self): + m = self.module() + tp = ir.LiteralStructType((flt, int1)) + gv = ir.GlobalVariable(m, tp, "myconstant") + c = gv.gep([ir.Constant(int32, x) for x in (0, 1)]) + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c), + 'getelementptr ({float, i1}, ptr @"myconstant", i32 0, i32 1)') # noqa E501 + else: + self.assertEqual(str(c), + 'getelementptr ({float, i1}, {float, i1}* @"myconstant", i32 0, i32 1)') # noqa E501 + self.assertEqual(c.type, ir.PointerType(int1)) + + const = ir.Constant(tp, None) + with self.assertRaises(TypeError): + const.gep([ir.Constant(int32, 0)]) + + const_ptr = ir.Constant(tp.as_pointer(), None) + c2 = const_ptr.gep([ir.Constant(int32, 0)]) + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c2), + 'getelementptr ({float, i1}, ptr null, i32 0)') # noqa E501 + else: + self.assertEqual(str(c2), + 'getelementptr ({float, i1}, {float, i1}* null, i32 0)') # noqa E501 + self.assertEqual(c.type, ir.PointerType(int1)) + + def test_gep_addrspace_globalvar(self): + m = self.module() + tp = ir.LiteralStructType((flt, int1)) + addrspace = 4 + + gv = ir.GlobalVariable(m, tp, "myconstant", addrspace=addrspace) + self.assertEqual(gv.addrspace, addrspace) + c = gv.gep([ir.Constant(int32, x) for x in (0, 1)]) + self.assertEqual(c.type.addrspace, addrspace) + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c), + ('getelementptr ({float, i1}, ptr ' + 'addrspace(4) @"myconstant", i32 0, i32 1)')) + else: + self.assertEqual(str(c), + ('getelementptr ({float, i1}, {float, i1} ' + 'addrspace(4)* @"myconstant", i32 0, i32 1)')) + self.assertEqual(c.type, ir.PointerType(int1, addrspace=addrspace)) + + def test_trunc(self): + c = ir.Constant(int64, 1).trunc(int32) + self.assertEqual(str(c), 'trunc (i64 1 to i32)') + + def test_zext(self): + c = ir.Constant(int32, 1).zext(int64) + self.assertEqual(str(c), 'zext (i32 1 to i64)') + + def test_sext(self): + c = ir.Constant(int32, -1).sext(int64) + self.assertEqual(str(c), 'sext (i32 -1 to i64)') + + def test_fptrunc(self): + c = ir.Constant(flt, 1).fptrunc(hlf) + self.assertEqual(str(c), 'fptrunc (float 0x3ff0000000000000 to half)') + + def test_fpext(self): + c = ir.Constant(flt, 1).fpext(dbl) + self.assertEqual(str(c), 'fpext (float 0x3ff0000000000000 to double)') + + def test_bitcast(self): + m = self.module() + gv = ir.GlobalVariable(m, int32, "myconstant") + c = gv.bitcast(int64.as_pointer()) + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c), 'bitcast (ptr @"myconstant" to ptr)') + else: + self.assertEqual(str(c), 'bitcast (i32* @"myconstant" to i64*)') + + def test_fptoui(self): + c = ir.Constant(flt, 1).fptoui(int32) + self.assertEqual(str(c), 'fptoui (float 0x3ff0000000000000 to i32)') + + def test_uitofp(self): + c = ir.Constant(int32, 1).uitofp(flt) + self.assertEqual(str(c), 'uitofp (i32 1 to float)') + + def test_fptosi(self): + c = ir.Constant(flt, 1).fptosi(int32) + self.assertEqual(str(c), 'fptosi (float 0x3ff0000000000000 to i32)') + + def test_sitofp(self): + c = ir.Constant(int32, 1).sitofp(flt) + self.assertEqual(str(c), 'sitofp (i32 1 to float)') + + def test_ptrtoint_1(self): + ptr = ir.Constant(int64.as_pointer(), None) + one = ir.Constant(int32, 1) + c = ptr.ptrtoint(int32) + + self.assertRaises(TypeError, one.ptrtoint, int64) + self.assertRaises(TypeError, ptr.ptrtoint, flt) + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c), 'ptrtoint (ptr null to i32)') + else: + self.assertEqual(str(c), 'ptrtoint (i64* null to i32)') + + def test_ptrtoint_2(self): + m = self.module() + gv = ir.GlobalVariable(m, int32, "myconstant") + c = gv.ptrtoint(int64) + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c), 'ptrtoint (ptr @"myconstant" to i64)') + + self.assertRaisesRegex( + TypeError, + r"can only ptrtoint\(\) to integer type, not 'ptr'", + gv.ptrtoint, + int64.as_pointer()) + else: + self.assertEqual(str(c), 'ptrtoint (i32* @"myconstant" to i64)') + + self.assertRaisesRegex( + TypeError, + r"can only ptrtoint\(\) to integer type, not 'i64\*'", + gv.ptrtoint, + int64.as_pointer()) + + c2 = ir.Constant(int32, 0) + self.assertRaisesRegex( + TypeError, + r"can only call ptrtoint\(\) on pointer type, not 'i32'", + c2.ptrtoint, + int64) + + def test_inttoptr(self): + one = ir.Constant(int32, 1) + pi = ir.Constant(flt, 3.14) + c = one.inttoptr(int64.as_pointer()) + + self.assertRaises(TypeError, one.inttoptr, int64) + self.assertRaises(TypeError, pi.inttoptr, int64.as_pointer()) + if not ir_layer_typed_pointers_enabled: + self.assertEqual(str(c), 'inttoptr (i32 1 to ptr)') + else: + self.assertEqual(str(c), 'inttoptr (i32 1 to i64*)') + + def test_neg(self): + one = ir.Constant(int32, 1) + self.assertEqual(str(one.neg()), 'sub (i32 0, i32 1)') + + def test_not(self): + one = ir.Constant(int32, 1) + self.assertEqual(str(one.not_()), 'xor (i32 1, i32 -1)') + + def test_fneg(self): + one = ir.Constant(flt, 1) + self.assertEqual(str(one.fneg()), 'fneg (float 0x3ff0000000000000)') + + def test_int_binops(self): + one = ir.Constant(int32, 1) + two = ir.Constant(int32, 2) + + oracle = {one.shl: 'shl', one.lshr: 'lshr', one.ashr: 'ashr', + one.add: 'add', one.sub: 'sub', one.mul: 'mul', + one.udiv: 'udiv', one.sdiv: 'sdiv', one.urem: 'urem', + one.srem: 'srem', one.or_: 'or', one.and_: 'and', + one.xor: 'xor'} + for fn, irop in oracle.items(): + self.assertEqual(str(fn(two)), irop + ' (i32 1, i32 2)') + + # unsigned integer compare + oracle = {'==': 'eq', '!=': 'ne', '>': + 'ugt', '>=': 'uge', '<': 'ult', '<=': 'ule'} + for cop, cond in oracle.items(): + actual = str(one.icmp_unsigned(cop, two)) + expected = 'icmp ' + cond + ' (i32 1, i32 2)' + self.assertEqual(actual, expected) + + # signed integer compare + oracle = {'==': 'eq', '!=': 'ne', + '>': 'sgt', '>=': 'sge', '<': 'slt', '<=': 'sle'} + for cop, cond in oracle.items(): + actual = str(one.icmp_signed(cop, two)) + expected = 'icmp ' + cond + ' (i32 1, i32 2)' + self.assertEqual(actual, expected) + + def test_flt_binops(self): + one = ir.Constant(flt, 1) + two = ir.Constant(flt, 2) + + oracle = {one.fadd: 'fadd', one.fsub: 'fsub', one.fmul: 'fmul', + one.fdiv: 'fdiv', one.frem: 'frem'} + for fn, irop in oracle.items(): + actual = str(fn(two)) + expected = irop + (' (float 0x3ff0000000000000,' + ' float 0x4000000000000000)') + self.assertEqual(actual, expected) + + # ordered float compare + oracle = {'==': 'oeq', '!=': 'one', '>': 'ogt', '>=': 'oge', + '<': 'olt', '<=': 'ole'} + for cop, cond in oracle.items(): + actual = str(one.fcmp_ordered(cop, two)) + expected = 'fcmp ' + cond + (' (float 0x3ff0000000000000,' + ' float 0x4000000000000000)') + self.assertEqual(actual, expected) + + # unordered float compare + oracle = {'==': 'ueq', '!=': 'une', '>': 'ugt', '>=': 'uge', + '<': 'ult', '<=': 'ule'} + for cop, cond in oracle.items(): + actual = str(one.fcmp_unordered(cop, two)) + expected = 'fcmp ' + cond + (' (float 0x3ff0000000000000,' + ' float 0x4000000000000000)') + self.assertEqual(actual, expected) + + +class TestTransforms(TestBase): + def test_call_transform(self): + mod = ir.Module() + foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "foo") + bar = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "bar") + builder = ir.IRBuilder() + builder.position_at_end(foo.append_basic_block()) + call = builder.call(foo, ()) + self.assertEqual(call.callee, foo) + modified = ir.replace_all_calls(mod, foo, bar) + self.assertIn(call, modified) + self.assertNotEqual(call.callee, foo) + self.assertEqual(call.callee, bar) + + +class TestSingleton(TestBase): + def test_undefined(self): + self.assertIs(ir.Undefined, ir.values._Undefined()) + self.assertIs(ir.Undefined, copy.copy(ir.Undefined)) + self.assertIs(ir.Undefined, copy.deepcopy(ir.Undefined)) + self.assert_pickle_correctly(ir.Undefined) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_refprune.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_refprune.py new file mode 100644 index 0000000000000000000000000000000000000000..b8225eb5611bcbe725b45508fdf3430808e109c4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_refprune.py @@ -0,0 +1,574 @@ +import unittest +from collections import defaultdict +from llvmlite import ir +from llvmlite import binding as llvm +from llvmlite.tests import TestCase + +import llvmlite.tests.refprune_proto as proto + + +def _iterate_cases(generate_test): + def wrap(fn): + def wrapped(self): + return generate_test(self, fn) + wrapped.__doc__ = f"generated test for {fn.__module__}.{fn.__name__}" + return wrapped + + for k, case_fn in proto.__dict__.items(): + if k.startswith('case'): + yield f'test_{k}', wrap(case_fn) + + +class PassManagerMixin(): + + def pb(self): + llvm.initialize_native_target() + tm = llvm.Target.from_default_triple().create_target_machine() + pto = llvm.create_pipeline_tuning_options(speed_level=0, size_level=0) + return llvm.create_pass_builder(tm, pto) + + +class TestRefPrunePrototype(TestCase): + """ + Test that the prototype is working. + """ + def generate_test(self, case_gen): + nodes, edges, expected = case_gen() + got = proto.FanoutAlgorithm(nodes, edges).run() + self.assertEqual(expected, got) + + # Generate tests + for name, case in _iterate_cases(generate_test): + locals()[name] = case + + +ptr_ty = ir.IntType(8).as_pointer() + + +class TestRefPrunePass(TestCase, PassManagerMixin): + """ + Test that the C++ implementation matches the expected behavior as for + the prototype. + + This generates a LLVM module for each test case, runs the pruner and checks + that the expected results are achieved. + """ + + def make_incref(self, m): + fnty = ir.FunctionType(ir.VoidType(), [ptr_ty]) + return ir.Function(m, fnty, name='NRT_incref') + + def make_decref(self, m): + fnty = ir.FunctionType(ir.VoidType(), [ptr_ty]) + return ir.Function(m, fnty, name='NRT_decref') + + def make_switcher(self, m): + fnty = ir.FunctionType(ir.IntType(32), ()) + return ir.Function(m, fnty, name='switcher') + + def make_brancher(self, m): + fnty = ir.FunctionType(ir.IntType(1), ()) + return ir.Function(m, fnty, name='brancher') + + def generate_ir(self, nodes, edges): + # Build LLVM module for the CFG + m = ir.Module() + + incref_fn = self.make_incref(m) + decref_fn = self.make_decref(m) + switcher_fn = self.make_switcher(m) + brancher_fn = self.make_brancher(m) + + fnty = ir.FunctionType(ir.VoidType(), [ptr_ty]) + fn = ir.Function(m, fnty, name='main') + [ptr] = fn.args + ptr.name = 'mem' + # populate the BB nodes + bbmap = {} + for bb in edges: + bbmap[bb] = fn.append_basic_block(bb) + # populate the BB + builder = ir.IRBuilder() + for bb, jump_targets in edges.items(): + builder.position_at_end(bbmap[bb]) + # Insert increfs and decrefs + for action in nodes[bb]: + if action == 'incref': + builder.call(incref_fn, [ptr]) + elif action == 'decref': + builder.call(decref_fn, [ptr]) + else: + raise AssertionError('unreachable') + + # Insert the terminator. + # Switch base on the number of jump targets. + n_targets = len(jump_targets) + if n_targets == 0: + builder.ret_void() + elif n_targets == 1: + [dst] = jump_targets + builder.branch(bbmap[dst]) + elif n_targets == 2: + [left, right] = jump_targets + sel = builder.call(brancher_fn, ()) + builder.cbranch(sel, bbmap[left], bbmap[right]) + elif n_targets > 2: + sel = builder.call(switcher_fn, ()) + [head, *tail] = jump_targets + + sw = builder.switch(sel, default=bbmap[head]) + for i, dst in enumerate(tail): + sw.add_case(sel.type(i), bbmap[dst]) + else: + raise AssertionError('unreachable') + + return m + + def apply_refprune(self, irmod): + mod = llvm.parse_assembly(str(irmod)) + pb = self.pb() + pm = pb.getModulePassManager() + pm.add_refprune_pass() + pm.run(mod, pb) + return mod + + def check(self, mod, expected, nodes): + # preprocess incref/decref locations + + # LLVM >= 18 adds an extra empty block "LoopExit" which causes + # regular dict to throw KeyError + d = defaultdict(lambda: defaultdict(int)) + + for k, vs in nodes.items(): + n_incref = vs.count('incref') + n_decref = vs.count('decref') + d[k] = {'incref': n_incref, 'decref': n_decref} + for k, stats in d.items(): + if expected.get(k): + stats['incref'] -= 1 + for dec_bb in expected[k]: + d[dec_bb]['decref'] -= 1 + + # find the main function + for f in mod.functions: + if f.name == 'main': + break + + # check each BB + for bb in f.blocks: + stats = d[bb.name] + text = str(bb) + n_incref = text.count('NRT_incref') + n_decref = text.count('NRT_decref') + self.assertEqual(stats['incref'], n_incref, msg=f'BB {bb}') + self.assertEqual(stats['decref'], n_decref, msg=f'BB {bb}') + + def generate_test(self, case_gen): + nodes, edges, expected = case_gen() + irmod = self.generate_ir(nodes, edges) + outmod = self.apply_refprune(irmod) + self.check(outmod, expected, nodes) + + # Generate tests + for name, case in _iterate_cases(generate_test): + locals()[name] = case + + +class BaseTestByIR(TestCase, PassManagerMixin): + refprune_bitmask = 0 + + prologue = r""" +declare void @NRT_incref(i8* %ptr) +declare void @NRT_decref(i8* %ptr) +""" + + def check(self, irmod, subgraph_limit=None): + mod = llvm.parse_assembly(f"{self.prologue}\n{irmod}") + pb = self.pb() + pm = pb.getModulePassManager() + if subgraph_limit is None: + pm.add_refprune_pass(self.refprune_bitmask) + else: + pm.add_refprune_pass(self.refprune_bitmask, + subgraph_limit=subgraph_limit) + before = llvm.dump_refprune_stats() + pm.run(mod, pb) + after = llvm.dump_refprune_stats() + return mod, after - before + + +class TestPerBB(BaseTestByIR): + refprune_bitmask = llvm.RefPruneSubpasses.PER_BB + + per_bb_ir_1 = r""" +define void @main(i8* %ptr) { + call void @NRT_incref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_bb_1(self): + mod, stats = self.check(self.per_bb_ir_1) + self.assertEqual(stats.basicblock, 2) + + per_bb_ir_2 = r""" +define void @main(i8* %ptr) { + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_bb_2(self): + mod, stats = self.check(self.per_bb_ir_2) + self.assertEqual(stats.basicblock, 4) + # not pruned + self.assertIn("call void @NRT_incref(ptr %ptr)", str(mod)) + + per_bb_ir_3 = r""" +define void @main(ptr %ptr, ptr %other) { + call void @NRT_incref(ptr %ptr) + call void @NRT_incref(ptr %ptr) + call void @NRT_decref(ptr %ptr) + call void @NRT_decref(ptr %other) + ret void +} +""" + + def test_per_bb_3(self): + mod, stats = self.check(self.per_bb_ir_3) + self.assertEqual(stats.basicblock, 2) + # not pruned + self.assertIn("call void @NRT_decref(ptr %other)", str(mod)) + + per_bb_ir_4 = r""" +; reordered +define void @main(ptr %ptr, ptr %other) { + call void @NRT_incref(ptr %ptr) + call void @NRT_decref(ptr %ptr) + call void @NRT_decref(ptr %ptr) + call void @NRT_decref(ptr %other) + call void @NRT_incref(ptr %ptr) + ret void +} +""" + + def test_per_bb_4(self): + mod, stats = self.check(self.per_bb_ir_4) + self.assertEqual(stats.basicblock, 4) + # not pruned + self.assertIn("call void @NRT_decref(ptr %other)", str(mod)) + + +class TestDiamond(BaseTestByIR): + refprune_bitmask = llvm.RefPruneSubpasses.DIAMOND + + per_diamond_1 = r""" +define void @main(i8* %ptr) { +bb_A: + call void @NRT_incref(i8* %ptr) + br label %bb_B +bb_B: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_1(self): + mod, stats = self.check(self.per_diamond_1) + self.assertEqual(stats.diamond, 2) + + per_diamond_2 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + br label %bb_D +bb_C: + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_2(self): + mod, stats = self.check(self.per_diamond_2) + self.assertEqual(stats.diamond, 2) + + per_diamond_3 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + br label %bb_D +bb_C: + call void @NRT_decref(i8* %ptr) ; reject because of decref in diamond + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_3(self): + mod, stats = self.check(self.per_diamond_3) + self.assertEqual(stats.diamond, 0) + + per_diamond_4 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_incref(i8* %ptr) ; extra incref will not affect prune + br label %bb_D +bb_C: + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_4(self): + mod, stats = self.check(self.per_diamond_4) + self.assertEqual(stats.diamond, 2) + + per_diamond_5 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + br label %bb_D +bb_C: + br label %bb_D +bb_D: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_per_diamond_5(self): + mod, stats = self.check(self.per_diamond_5) + self.assertEqual(stats.diamond, 4) + + +class TestFanout(BaseTestByIR): + """More complex cases are tested in TestRefPrunePass + """ + + refprune_bitmask = llvm.RefPruneSubpasses.FANOUT + + fanout_1 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret void +bb_C: + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_fanout_1(self): + mod, stats = self.check(self.fanout_1) + self.assertEqual(stats.fanout, 3) + + fanout_2 = r""" +define void @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret void +bb_C: + call void @NRT_decref(i8* %ptr) + br label %bb_B ; illegal jump to other decref +} +""" + + def test_fanout_2(self): + mod, stats = self.check(self.fanout_2) + self.assertEqual(stats.fanout, 0) + + fanout_3 = r""" +define void @main(i8* %ptr, i1 %cond) { +bb_A: + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +bb_C: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret void +} +""" + + def test_fanout_3(self): + mod, stats = self.check(self.fanout_3) + self.assertEqual(stats.fanout, 6) + + def test_fanout_3_limited(self): + # With subgraph limit at 1, it is essentially turning off the fanout + # pruner. + mod, stats = self.check(self.fanout_3, subgraph_limit=1) + self.assertEqual(stats.fanout, 0) + + +class TestFanoutRaise(BaseTestByIR): + refprune_bitmask = llvm.RefPruneSubpasses.FANOUT_RAISE + + fanout_raise_1 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + ret i32 1 +} +!0 = !{i1 true} +""" + + def test_fanout_raise_1(self): + mod, stats = self.check(self.fanout_raise_1) + self.assertEqual(stats.fanout_raise, 2) + + fanout_raise_2 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_C: + store i8* null, i8** %excinfo, !numba_exception_typo !0 ; bad metadata + ret i32 1 +} + +!0 = !{i1 true} +""" + + def test_fanout_raise_2(self): + # This is ensuring that fanout_raise is not pruning when the metadata + # is incorrectly named. + mod, stats = self.check(self.fanout_raise_2) + self.assertEqual(stats.fanout_raise, 0) + + fanout_raise_3 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + ret i32 1 +} + +!0 = !{i32 1} ; ok; use i32 +""" + + def test_fanout_raise_3(self): + mod, stats = self.check(self.fanout_raise_3) + self.assertEqual(stats.fanout_raise, 2) + + fanout_raise_4 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + ret i32 1 ; BAD; all tails are raising without decref +bb_C: + ret i32 1 ; BAD; all tails are raising without decref +} + +!0 = !{i1 1} +""" + + def test_fanout_raise_4(self): + mod, stats = self.check(self.fanout_raise_4) + self.assertEqual(stats.fanout_raise, 0) + + fanout_raise_5 = r""" +define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + br i1 %cond, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + br label %common.ret +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + br label %common.ret +common.ret: + %common.ret.op = phi i32 [ 0, %bb_B ], [ 1, %bb_C ] + ret i32 %common.ret.op +} +!0 = !{i1 1} +""" + + def test_fanout_raise_5(self): + mod, stats = self.check(self.fanout_raise_5) + self.assertEqual(stats.fanout_raise, 2) + + # test case 6 is from https://github.com/numba/llvmlite/issues/1023 + fanout_raise_6 = r""" +define i32 @main(i8* %ptr, i1 %cond1, i1 %cond2, i1 %cond3, i8** %excinfo) { +bb_A: + call void @NRT_incref(i8* %ptr) + call void @NRT_incref(i8* %ptr) + br i1 %cond1, label %bb_B, label %bb_C +bb_B: + call void @NRT_decref(i8* %ptr) + br i1 %cond2, label %bb_D, label %bb_E +bb_C: + store i8* null, i8** %excinfo, !numba_exception_output !0 + ret i32 1 +bb_D: + call void @NRT_decref(i8* %ptr) + ret i32 0 +bb_E: + call void @NRT_incref(i8* %ptr) + br i1 %cond3, label %bb_F, label %bb_C +bb_F: + call void @NRT_decref(i8* %ptr) + call void @NRT_decref(i8* %ptr) + ret i32 0 +} +!0 = !{i1 1} +""" + + def test_fanout_raise_6(self): + mod, stats = self.check(self.fanout_raise_6) + self.assertEqual(stats.fanout_raise, 7) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_valuerepr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_valuerepr.py new file mode 100644 index 0000000000000000000000000000000000000000..f8d7e4b2c073ecdfd5ae8c985ebd9108245bd78f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite/tests/test_valuerepr.py @@ -0,0 +1,60 @@ +import math +import sys +import unittest + +from llvmlite.ir import ( + Constant, FloatType, DoubleType, LiteralStructType, IntType, + ArrayType, HalfType) +from llvmlite.tests import TestCase + + +int8 = IntType(8) +int16 = IntType(16) + + +PY36_OR_LATER = sys.version_info[:2] >= (3, 6) + + +class TestValueRepr(TestCase): + + def test_double_repr(self): + def check_repr(val, expected): + c = Constant(DoubleType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "double 0x400921fb54442d18") + check_repr(float('inf'), "double 0x7ff0000000000000") + check_repr(float('-inf'), "double 0xfff0000000000000") + + def test_float_repr(self): + def check_repr(val, expected): + c = Constant(FloatType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "float 0x400921fb60000000") + check_repr(float('inf'), "float 0x7ff0000000000000") + check_repr(float('-inf'), "float 0xfff0000000000000") + + @unittest.skipUnless(PY36_OR_LATER, 'py36+ only') + def test_half_repr(self): + def check_repr(val, expected): + c = Constant(HalfType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "half 0x4009200000000000") + check_repr(float('inf'), "half 0x7ff0000000000000") + check_repr(float('-inf'), "half 0xfff0000000000000") + + def test_struct_repr(self): + tp = LiteralStructType([int8, int16]) + c = Constant(tp, (Constant(int8, 100), Constant(int16, 1000))) + self.assertEqual(str(c), "{i8, i16} {i8 100, i16 1000}") + + def test_array_repr(self): + tp = ArrayType(int8, 3) + values = [Constant(int8, x) for x in (5, 10, -15)] + c = Constant(tp, values) + self.assertEqual(str(c), "[3 x i8] [i8 5, i8 10, i8 -15]") + c = Constant(tp, bytearray(b"\x01\x02\x03")) + self.assertEqual(str(c), '[3 x i8] c"\\01\\02\\03"') + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/lxml-6.1.1.dist-info/licenses/LICENSE.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/lxml-6.1.1.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..0bdf03913ffdfd09be5a524c9303bd54a132d450 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/lxml-6.1.1.dist-info/licenses/LICENSE.txt @@ -0,0 +1,31 @@ +BSD 3-Clause License + +Copyright (c) 2004 Infrae. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. 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. + + 3. Neither the name of Infrae 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 INFRAE 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/data/conda_envs/evalclaw/lib/python3.11/site-packages/lxml-6.1.1.dist-info/licenses/LICENSES.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/lxml-6.1.1.dist-info/licenses/LICENSES.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f97c18aa0b162ffcc3e745d80efb9def1c82515 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/lxml-6.1.1.dist-info/licenses/LICENSES.txt @@ -0,0 +1,29 @@ +lxml is copyright Infrae and distributed under the BSD license (see +doc/licenses/BSD.txt), with the following exceptions: + +Some code, such a selftest.py, selftest2.py and +src/lxml/_elementpath.py are derived from ElementTree and +cElementTree. See doc/licenses/elementtree.txt for the license text. + +lxml.cssselect and lxml.html are copyright Ian Bicking and distributed +under the BSD license (see doc/licenses/BSD.txt). + +test.py, the test-runner script, is GPL and copyright Shuttleworth +Foundation. See doc/licenses/GPL.txt. It is believed the unchanged +inclusion of test.py to run the unit test suite falls under the +"aggregation" clause of the GPL and thus does not affect the license +of the rest of the package. + +The isoschematron implementation uses several XSL and RelaxNG resources: + * The (XML syntax) RelaxNG schema for schematron, copyright International + Organization for Standardization (see + src/lxml/isoschematron/resources/rng/iso-schematron.rng for the license + text) + * The skeleton iso-schematron-xlt1 pure-xslt schematron implementation + xsl stylesheets, copyright Rick Jelliffe and Academia Sinica Computing + Center, Taiwan (see the xsl files here for the license text: + src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/) + * The xsd/rng schema schematron extraction xsl transformations are unlicensed + and copyright the respective authors as noted (see + src/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl and + src/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b70899e95f490640c1836068df3a427cb37c5efd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82345066884696300ad327922a0d64e834e54fb4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/_generated_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/_generated_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a0fe8643206c47cf5f19c15110c4c0359e0ec19 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/_generated_version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/acero.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/acero.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c0d7ef2b49d9ce219205c92ca86e371a08536fb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/acero.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/benchmark.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/benchmark.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51acb81e6e8e20045f555178cd215feb353627fd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/benchmark.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/cffi.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/cffi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eb1eac453d90e098684aa69b80ddc44ba00166f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/cffi.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/compute.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/compute.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33fcae2d43ab7c24c674781bd43a644872ae5af7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/compute.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/conftest.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aea7aecae86206df03ebcc1d8f5b23ea2954bb22 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/conftest.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/csv.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/csv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f2688f2208e5ef5dfbfb2b8d6dac75977026311 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/csv.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/cuda.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/cuda.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..667095df3a51f54000dcacd693784987799e6b5b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/cuda.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/dataset.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98aa447151849bfb4b4cfe4a65bdbb49cd04cddf Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/dataset.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/feather.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/feather.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bbcc431ef9b965b3ace245aee9b314d491366aa Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/feather.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/flight.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/flight.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce036dc7c2c6691ddb85e3efb6c754a3b019b4ed Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/flight.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/fs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/fs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bc1e091eccd9fb936e710402e11e08fce408256 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/fs.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/ipc.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/ipc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f25ec697e40d6666aa0021785dcf0ec83ed97608 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/ipc.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/json.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/json.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ebb5615732cc37771bc598cf2d45b6d396055f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/json.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/jvm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/jvm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e76f457ace9a0a5325e359fc7a651341eedd48b4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/jvm.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/orc.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/orc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97f6ab62cdaaa2f968d3b4f6101c0d28f421c93c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/orc.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/pandas_compat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/pandas_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e4720aca270f9afec7c40c63bc666028b186007 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/pandas_compat.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/substrait.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/substrait.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2502ff563ad38500cd12afe0c67a810f5456584 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/substrait.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a575210cc89bad30fa74f8e374b2b6f645759dc6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/types.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/util.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9570c331e5db0f88bb0b7204b8b8c3511abc52a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/__pycache__/util.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/accumulation_queue.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/accumulation_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..b0e0b85a4f3d0504ad0e09237e498c001c55f96a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/accumulation_queue.h @@ -0,0 +1,162 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/acero/visibility.h" +#include "arrow/compute/exec.h" +#include "arrow/result.h" + +namespace arrow { +namespace acero { +namespace util { + +using arrow::compute::ExecBatch; + +/// \brief A container that accumulates batches until they are ready to +/// be processed. +class ARROW_ACERO_EXPORT AccumulationQueue { + public: + AccumulationQueue() : row_count_(0) {} + ~AccumulationQueue() = default; + + // We should never be copying ExecBatch around + AccumulationQueue(const AccumulationQueue&) = delete; + AccumulationQueue& operator=(const AccumulationQueue&) = delete; + + AccumulationQueue(AccumulationQueue&& that); + AccumulationQueue& operator=(AccumulationQueue&& that); + + void Concatenate(AccumulationQueue&& that); + void InsertBatch(ExecBatch batch); + int64_t row_count() { return row_count_; } + size_t batch_count() { return batches_.size(); } + bool empty() const { return batches_.empty(); } + void Clear(); + ExecBatch& operator[](size_t i); + + private: + int64_t row_count_; + std::vector batches_; +}; + +/// A queue that sequences incoming batches +/// +/// This can be used when a node needs to do some kind of ordered processing on +/// the stream. +/// +/// Batches can be inserted in any order. The process_callback will be called on +/// the batches, in order, without reentrant calls. For this reason the callback +/// should be quick. +/// +/// For example, in a top-n node, the process callback should determine how many +/// rows need to be delivered for the given batch, and then return a task to actually +/// deliver those rows. +class ARROW_ACERO_EXPORT SequencingQueue { + public: + using Task = std::function; + + /// Strategy that describes how to handle items + class Processor { + public: + /// Process the batch, potentially generating a task + /// + /// This method will be called on each batch in order. Calls to this method + /// will be serialized and it will not be called reentrantly. This makes it + /// safe to do things that rely on order but minimal time should be spent here + /// to avoid becoming a bottleneck. + /// + /// \return a follow-up task that will be scheduled. The follow-up task(s) are + /// is not guaranteed to run in any particular order. If nullopt is + /// returned then nothing will be scheduled. + virtual Result> Process(ExecBatch batch) = 0; + /// Schedule a task + virtual void Schedule(Task task) = 0; + }; + + virtual ~SequencingQueue() = default; + + /// Insert a batch into the queue + /// + /// This will insert the batch into the queue. If this batch was the next batch + /// to deliver then this will trigger 1+ calls to the process callback to generate + /// 1+ tasks. + /// + /// The task generated by this call will be executed immediately. The remaining + /// tasks will be scheduled using the schedule callback. + /// + /// From a data pipeline perspective the sequencing queue is a "sometimes" breaker. If + /// a task arrives in order then this call will usually execute the downstream pipeline. + /// If this task arrives early then this call will only queue the data. + virtual Status InsertBatch(ExecBatch batch) = 0; + + /// Create a queue + /// \param processor describes how to process the batches, must outlive the queue + static std::unique_ptr Make(Processor* processor); +}; + +/// A queue that sequences incoming batches +/// +/// Unlike SequencingQueue the Process method is not expected to schedule new tasks. +/// +/// If a batch arrives and another thread is currently processing then the batch +/// will be queued and control will return. In other words, delivery of batches will +/// not block on the Process method. +/// +/// It can be helpful to think of this as if a dedicated thread is running Process as +/// batches arrive +class ARROW_ACERO_EXPORT SerialSequencingQueue { + public: + /// Strategy that describes how to handle items + class Processor { + public: + virtual ~Processor() = default; + /// Process the batch + /// + /// This method will be called on each batch in order. Calls to this method + /// will be serialized and it will not be called reentrantly. This makes it + /// safe to do things that rely on order. + /// + /// If this falls behind then data may accumulate + /// + /// TODO: Could add backpressure if needed but right now all uses of this should + /// be pretty fast and so are unlikely to block. + virtual Status Process(ExecBatch batch) = 0; + }; + + virtual ~SerialSequencingQueue() = default; + + /// Insert a batch into the queue + /// + /// This will insert the batch into the queue. If this batch was the next batch + /// to deliver then this may trigger calls to the processor which will be run + /// as part of this call. + virtual Status InsertBatch(ExecBatch batch) = 0; + + /// Create a queue + /// \param processor describes how to process the batches, must outlive the queue + static std::unique_ptr Make(Processor* processor); +}; + +} // namespace util +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/aggregate_node.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/aggregate_node.h new file mode 100644 index 0000000000000000000000000000000000000000..0c6fea16a8acc75046309708221189d368f605c0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/aggregate_node.h @@ -0,0 +1,58 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include + +#include "arrow/acero/visibility.h" +#include "arrow/compute/api_aggregate.h" +#include "arrow/compute/test_util_internal.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/result.h" +#include "arrow/type_fwd.h" + +namespace arrow { +namespace acero { +namespace aggregate { + +using compute::Aggregate; +using compute::default_exec_context; +using compute::ExecContext; + +/// \brief Make the output schema of an aggregate node +/// +/// The output schema is determined by the aggregation kernels, which may depend on the +/// ExecContext argument. To guarantee correct results, the same ExecContext argument +/// should be used in execution. +/// +/// \param[in] input_schema the schema of the input to the node +/// \param[in] keys the grouping keys for the aggregation +/// \param[in] segment_keys the segmenting keys for the aggregation +/// \param[in] aggregates the aggregates for the aggregation +/// \param[in] exec_ctx the execution context for the aggregation +ARROW_ACERO_EXPORT Result> MakeOutputSchema( + const std::shared_ptr& input_schema, const std::vector& keys, + const std::vector& segment_keys, const std::vector& aggregates, + ExecContext* exec_ctx = default_exec_context()); + +} // namespace aggregate +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/api.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/api.h new file mode 100644 index 0000000000000000000000000000000000000000..c9724fd512d0b56dfa3a24647b3885677c92b534 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/api.h @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle + +#pragma once + +/// \defgroup acero-api Utilities for creating and executing execution plans +/// @{ +/// @} + +/// \defgroup acero-nodes Options classes for the various exec nodes +/// @{ +/// @} + +#include "arrow/acero/exec_plan.h" +#include "arrow/acero/options.h" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/asof_join_node.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/asof_join_node.h new file mode 100644 index 0000000000000000000000000000000000000000..6a0ce8fd386b01ac868bac3d4d026a309e351cb3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/asof_join_node.h @@ -0,0 +1,41 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include + +#include "arrow/acero/options.h" +#include "arrow/acero/visibility.h" +#include "arrow/compute/exec.h" +#include "arrow/type.h" + +namespace arrow { +namespace acero { +namespace asofjoin { + +using AsofJoinKeys = AsofJoinNodeOptions::Keys; + +/// \brief Make the output schema of an as-of-join node +/// +/// \param[in] input_schema the schema of each input to the node +/// \param[in] input_keys the key of each input to the node +ARROW_ACERO_EXPORT Result> MakeOutputSchema( + const std::vector>& input_schema, + const std::vector& input_keys); + +} // namespace asofjoin +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/backpressure_handler.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/backpressure_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..c6a47e60197a51f85c2279f00ff8851c78a264f5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/backpressure_handler.h @@ -0,0 +1,64 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once +#include "arrow/acero/exec_plan.h" +#include "arrow/acero/options.h" + +#include + +namespace arrow::acero { + +class BackpressureHandler { + private: + BackpressureHandler(size_t low_threshold, size_t high_threshold, + std::unique_ptr backpressure_control) + : low_threshold_(low_threshold), + high_threshold_(high_threshold), + backpressure_control_(std::move(backpressure_control)) {} + + public: + static Result Make( + size_t low_threshold, size_t high_threshold, + std::unique_ptr backpressure_control) { + if (low_threshold >= high_threshold) { + return Status::Invalid("low threshold (", low_threshold, + ") must be less than high threshold (", high_threshold, ")"); + } + if (backpressure_control == NULLPTR) { + return Status::Invalid("null backpressure control parameter"); + } + BackpressureHandler backpressure_handler(low_threshold, high_threshold, + std::move(backpressure_control)); + return backpressure_handler; + } + + void Handle(size_t start_level, size_t end_level) { + if (start_level < high_threshold_ && end_level >= high_threshold_) { + backpressure_control_->Pause(); + } else if (start_level > low_threshold_ && end_level <= low_threshold_) { + backpressure_control_->Resume(); + } + } + + private: + size_t low_threshold_; + size_t high_threshold_; + std::unique_ptr backpressure_control_; +}; + +} // namespace arrow::acero diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/benchmark_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/benchmark_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0ba8553887c03f876b6e08f031f5641170c2e09f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/benchmark_util.h @@ -0,0 +1,48 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "benchmark/benchmark.h" + +#include "arrow/acero/exec_plan.h" +#include "arrow/acero/test_util_internal.h" +#include "arrow/compute/exec.h" + +namespace arrow { + +namespace acero { + +Status BenchmarkNodeOverhead(benchmark::State& state, int32_t num_batches, + int32_t batch_size, arrow::acero::BatchesWithSchema data, + std::vector& node_declarations, + arrow::MemoryPool* pool = default_memory_pool()); + +Status BenchmarkIsolatedNodeOverhead(benchmark::State& state, + arrow::compute::Expression expr, int32_t num_batches, + int32_t batch_size, + arrow::acero::BatchesWithSchema data, + std::string factory_name, + arrow::acero::ExecNodeOptions& options, + arrow::MemoryPool* pool = default_memory_pool()); + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/bloom_filter.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/bloom_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..8f9fe171baeb39f5347d112921666ba057cb56b6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/bloom_filter.h @@ -0,0 +1,323 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/acero/partition_util.h" +#include "arrow/acero/util.h" +#include "arrow/memory_pool.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/simd.h" + +namespace arrow { +namespace acero { + +// A set of pre-generated bit masks from a 64-bit word. +// +// It is used to map selected bits of hash to a bit mask that will be used in +// a Bloom filter. +// +// These bit masks need to look random and need to have a similar fractions of +// bits set in order for a Bloom filter to have a low false positives rate. +// +struct ARROW_ACERO_EXPORT BloomFilterMasks { + // Generate all masks as a single bit vector. Each bit offset in this bit + // vector corresponds to a single mask. + // In each consecutive kBitsPerMask bits, there must be between + // kMinBitsSet and kMaxBitsSet bits set. + // + BloomFilterMasks(); + + inline uint64_t mask(int bit_offset) { +#if ARROW_LITTLE_ENDIAN + return (arrow::util::SafeLoadAs(masks_ + bit_offset / 8) >> + (bit_offset % 8)) & + kFullMask; +#else + return (BYTESWAP(arrow::util::SafeLoadAs(masks_ + bit_offset / 8)) >> + (bit_offset % 8)) & + kFullMask; +#endif + } + + // Masks are 57 bits long because then they can be accessed at an + // arbitrary bit offset using a single unaligned 64-bit load instruction. + // + static constexpr int kBitsPerMask = 57; + static constexpr uint64_t kFullMask = (1ULL << kBitsPerMask) - 1; + + // Minimum and maximum number of bits set in each mask. + // This constraint is enforced when generating the bit masks. + // Values should be close to each other and chosen as to minimize a Bloom + // filter false positives rate. + // + static constexpr int kMinBitsSet = 4; + static constexpr int kMaxBitsSet = 5; + + // Number of generated masks. + // Having more masks to choose will improve false positives rate of Bloom + // filter but will also use more memory, which may lead to more CPU cache + // misses. + // The chosen value results in using only a few cache-lines for mask lookups, + // while providing a good variety of available bit masks. + // + static constexpr int kLogNumMasks = 10; + static constexpr int kNumMasks = 1 << kLogNumMasks; + + // Data of masks. Masks are stored in a single bit vector. Nth mask is + // kBitsPerMask bits starting at bit offset N. + // + static constexpr int kTotalBytes = (kNumMasks + 64) / 8; + uint8_t masks_[kTotalBytes]; +}; + +// A variant of a blocked Bloom filter implementation. +// A Bloom filter is a data structure that provides approximate membership test +// functionality based only on the hash of the key. Membership test may return +// false positives but not false negatives. Approximation of the result allows +// in general case (for arbitrary data types of keys) to save on both memory and +// lookup cost compared to the accurate membership test. +// The accurate test may sometimes still be cheaper for a specific data types +// and inputs, e.g. integers from a small range. +// +// This blocked Bloom filter is optimized for use in hash joins, to achieve a +// good balance between the size of the filter, the cost of its building and +// querying and the rate of false positives. +// +class ARROW_ACERO_EXPORT BlockedBloomFilter { + friend class BloomFilterBuilder_SingleThreaded; + friend class BloomFilterBuilder_Parallel; + + public: + BlockedBloomFilter() : log_num_blocks_(0), num_blocks_(0), blocks_(NULLPTR) {} + + inline bool Find(uint64_t hash) const { + uint64_t m = mask(hash); + uint64_t b = blocks_[block_id(hash)]; + return (b & m) == m; + } + + // Uses SIMD if available for smaller Bloom filters. + // Uses memory prefetching for larger Bloom filters. + // + void Find(int64_t hardware_flags, int64_t num_rows, const uint32_t* hashes, + uint8_t* result_bit_vector, bool enable_prefetch = true) const; + void Find(int64_t hardware_flags, int64_t num_rows, const uint64_t* hashes, + uint8_t* result_bit_vector, bool enable_prefetch = true) const; + + int log_num_blocks() const { return log_num_blocks_; } + + int NumHashBitsUsed() const; + + bool IsSameAs(const BlockedBloomFilter* other) const; + + int64_t NumBitsSet() const; + + // Folding of a block Bloom filter after the initial version + // has been built. + // + // One of the parameters for creation of Bloom filter is the number + // of bits allocated for it. The more bits allocated, the lower the + // probability of false positives. A good heuristic is to aim for + // half of the bits set in the constructed Bloom filter. This should + // result in a good trade off between size (and following cost of + // memory accesses) and false positives rate. + // + // There might have been many duplicate keys in the input provided + // to Bloom filter builder. In that case the resulting bit vector + // would be more sparse then originally intended. It is possible to + // easily correct that and cut in half the size of Bloom filter + // after it has already been constructed. The process to do that is + // approximately equal to OR-ing bits from upper and lower half (the + // way we address these bits when inserting or querying a hash makes + // such folding in half possible). + // + // We will keep folding as long as the fraction of bits set is less + // than 1/4. The resulting bit vector density should be in the [1/4, + // 1/2) range. + // + void Fold(); + + private: + Status CreateEmpty(int64_t num_rows_to_insert, MemoryPool* pool); + + inline void Insert(uint64_t hash) { + uint64_t m = mask(hash); + uint64_t& b = blocks_[block_id(hash)]; + b |= m; + } + + void Insert(int64_t hardware_flags, int64_t num_rows, const uint32_t* hashes); + void Insert(int64_t hardware_flags, int64_t num_rows, const uint64_t* hashes); + + inline uint64_t mask(uint64_t hash) const { + // The lowest bits of hash are used to pick mask index. + // + int mask_id = static_cast(hash & (BloomFilterMasks::kNumMasks - 1)); + uint64_t result = masks_.mask(mask_id); + + // The next set of hash bits is used to pick the amount of bit + // rotation of the mask. + // + int rotation = (hash >> BloomFilterMasks::kLogNumMasks) & 63; + result = ROTL64(result, rotation); + + return result; + } + + inline int64_t block_id(uint64_t hash) const { + // The next set of hash bits following the bits used to select a + // mask is used to pick block id (index of 64-bit word in a bit + // vector). + // + return (hash >> (BloomFilterMasks::kLogNumMasks + 6)) & (num_blocks_ - 1); + } + + template + inline void InsertImp(int64_t num_rows, const T* hashes); + + template + inline void FindImp(int64_t num_rows, const T* hashes, uint8_t* result_bit_vector, + bool enable_prefetch) const; + + void SingleFold(int num_folds); + +#if defined(ARROW_HAVE_RUNTIME_AVX2) + inline __m256i mask_avx2(__m256i hash) const; + inline __m256i block_id_avx2(__m256i hash) const; + int64_t Insert_avx2(int64_t num_rows, const uint32_t* hashes); + int64_t Insert_avx2(int64_t num_rows, const uint64_t* hashes); + template + int64_t InsertImp_avx2(int64_t num_rows, const T* hashes); + int64_t Find_avx2(int64_t num_rows, const uint32_t* hashes, + uint8_t* result_bit_vector) const; + int64_t Find_avx2(int64_t num_rows, const uint64_t* hashes, + uint8_t* result_bit_vector) const; + template + int64_t FindImp_avx2(int64_t num_rows, const T* hashes, + uint8_t* result_bit_vector) const; +#endif + + bool UsePrefetch() const { + return num_blocks_ * sizeof(uint64_t) > kPrefetchLimitBytes; + } + + static constexpr int64_t kPrefetchLimitBytes = 256 * 1024; + + static BloomFilterMasks masks_; + + // Total number of bits used by block Bloom filter must be a power + // of 2. + // + int log_num_blocks_; + int64_t num_blocks_; + + // Buffer allocated to store an array of power of 2 64-bit blocks. + // + std::shared_ptr buf_; + // Pointer to mutable data owned by Buffer + // + uint64_t* blocks_; +}; + +// We have two separate implementations of building a Bloom filter, multi-threaded and +// single-threaded. +// +// Single threaded version is useful in two ways: +// a) It allows to verify parallel implementation in tests (the single threaded one is +// simpler and can be used as the source of truth). +// b) It is preferred for small and medium size Bloom filters, because it skips extra +// synchronization related steps from parallel variant (partitioning and taking locks). +// +enum class BloomFilterBuildStrategy { + SINGLE_THREADED = 0, + PARALLEL = 1, +}; + +class ARROW_ACERO_EXPORT BloomFilterBuilder { + public: + virtual ~BloomFilterBuilder() = default; + virtual Status Begin(size_t num_threads, int64_t hardware_flags, MemoryPool* pool, + int64_t num_rows, int64_t num_batches, + BlockedBloomFilter* build_target) = 0; + virtual int64_t num_tasks() const { return 0; } + virtual Status PushNextBatch(size_t thread_index, int64_t num_rows, + const uint32_t* hashes) = 0; + virtual Status PushNextBatch(size_t thread_index, int64_t num_rows, + const uint64_t* hashes) = 0; + virtual void CleanUp() {} + static std::unique_ptr Make(BloomFilterBuildStrategy strategy); +}; + +class ARROW_ACERO_EXPORT BloomFilterBuilder_SingleThreaded : public BloomFilterBuilder { + public: + Status Begin(size_t num_threads, int64_t hardware_flags, MemoryPool* pool, + int64_t num_rows, int64_t num_batches, + BlockedBloomFilter* build_target) override; + + Status PushNextBatch(size_t /*thread_index*/, int64_t num_rows, + const uint32_t* hashes) override; + + Status PushNextBatch(size_t /*thread_index*/, int64_t num_rows, + const uint64_t* hashes) override; + + private: + template + void PushNextBatchImp(int64_t num_rows, const T* hashes); + + int64_t hardware_flags_; + BlockedBloomFilter* build_target_; +}; + +class ARROW_ACERO_EXPORT BloomFilterBuilder_Parallel : public BloomFilterBuilder { + public: + Status Begin(size_t num_threads, int64_t hardware_flags, MemoryPool* pool, + int64_t num_rows, int64_t num_batches, + BlockedBloomFilter* build_target) override; + + Status PushNextBatch(size_t thread_id, int64_t num_rows, + const uint32_t* hashes) override; + + Status PushNextBatch(size_t thread_id, int64_t num_rows, + const uint64_t* hashes) override; + + void CleanUp() override; + + private: + template + void PushNextBatchImp(size_t thread_id, int64_t num_rows, const T* hashes); + + int64_t hardware_flags_; + BlockedBloomFilter* build_target_; + int log_num_prtns_; + struct ThreadLocalState { + std::vector partitioned_hashes_32; + std::vector partitioned_hashes_64; + std::vector partition_ranges; + std::vector unprocessed_partition_ids; + }; + std::vector thread_local_states_; + PartitionLocks prtn_locks_; +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/exec_plan.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/exec_plan.h new file mode 100644 index 0000000000000000000000000000000000000000..dba6c64ddc8379f7a8e6aa666f55555ced6c78aa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/exec_plan.h @@ -0,0 +1,819 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/acero/type_fwd.h" +#include "arrow/acero/visibility.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/exec.h" +#include "arrow/compute/ordering.h" +#include "arrow/type_fwd.h" +#include "arrow/util/future.h" +#include "arrow/util/macros.h" +#include "arrow/util/tracing.h" +#include "arrow/util/type_fwd.h" + +namespace arrow { + +using compute::ExecBatch; +using compute::ExecContext; +using compute::FunctionRegistry; +using compute::GetFunctionRegistry; +using compute::Ordering; +using compute::threaded_exec_context; + +namespace acero { + +/// \addtogroup acero-internals +/// @{ + +class ARROW_ACERO_EXPORT ExecPlan : public std::enable_shared_from_this { + public: + // This allows operators to rely on signed 16-bit indices + static const uint32_t kMaxBatchSize = 1 << 15; + using NodeVector = std::vector; + + virtual ~ExecPlan() = default; + + QueryContext* query_context(); + + /// \brief retrieve the nodes in the plan + const NodeVector& nodes() const; + + /// Make an empty exec plan + static Result> Make( + QueryOptions options, ExecContext exec_context = *threaded_exec_context(), + std::shared_ptr metadata = NULLPTR); + + static Result> Make( + ExecContext exec_context = *threaded_exec_context(), + std::shared_ptr metadata = NULLPTR); + + static Result> Make( + QueryOptions options, ExecContext* exec_context, + std::shared_ptr metadata = NULLPTR); + + static Result> Make( + ExecContext* exec_context, + std::shared_ptr metadata = NULLPTR); + + ExecNode* AddNode(std::unique_ptr node); + + template + Node* EmplaceNode(Args&&... args) { + std::unique_ptr node{new Node{std::forward(args)...}}; + auto out = node.get(); + AddNode(std::move(node)); + return out; + } + + Status Validate(); + + /// \brief Start producing on all nodes + /// + /// Nodes are started in reverse topological order, such that any node + /// is started before all of its inputs. + void StartProducing(); + + /// \brief Stop producing on all nodes + /// + /// Triggers all sources to stop producing new data. In order to cleanly stop the plan + /// will continue to run any tasks that are already in progress. The caller should + /// still wait for `finished` to complete before destroying the plan. + void StopProducing(); + + /// \brief A future which will be marked finished when all tasks have finished. + Future<> finished(); + + /// \brief Return whether the plan has non-empty metadata + bool HasMetadata() const; + + /// \brief Return the plan's attached metadata + std::shared_ptr metadata() const; + + std::string ToString() const; +}; + +// Acero can be extended by providing custom implementations of ExecNode. The methods +// below are documented in detail and provide careful instruction on how to fulfill the +// ExecNode contract. It's suggested you familiarize yourself with the Acero +// documentation in the C++ user guide. +class ARROW_ACERO_EXPORT ExecNode { + public: + using NodeVector = std::vector; + + virtual ~ExecNode() = default; + + virtual const char* kind_name() const = 0; + + // The number of inputs expected by this node + int num_inputs() const { return static_cast(inputs_.size()); } + + /// This node's predecessors in the exec plan + const NodeVector& inputs() const { return inputs_; } + + /// True if the plan has no output schema (is a sink) + bool is_sink() const { return !output_schema_; } + + /// \brief Labels identifying the function of each input. + const std::vector& input_labels() const { return input_labels_; } + + /// This node's successor in the exec plan + const ExecNode* output() const { return output_; } + + /// The datatypes for batches produced by this node + const std::shared_ptr& output_schema() const { return output_schema_; } + + /// This node's exec plan + ExecPlan* plan() { return plan_; } + + /// \brief An optional label, for display and debugging + /// + /// There is no guarantee that this value is non-empty or unique. + const std::string& label() const { return label_; } + void SetLabel(std::string label) { label_ = std::move(label); } + + virtual Status Validate() const; + + /// \brief the ordering of the output batches + /// + /// This does not guarantee the batches will be emitted by this node + /// in order. Instead it guarantees that the batches will have their + /// ExecBatch::index property set in a way that respects this ordering. + /// + /// In other words, given the ordering {{"x", SortOrder::Ascending}} we + /// know that all values of x in a batch with index N will be less than + /// or equal to all values of x in a batch with index N+k (assuming k > 0). + /// Furthermore, we also know that values will be sorted within a batch. + /// Any row N will have a value of x that is less than the value for + /// any row N+k. + /// + /// Note that an ordering can be both Ordering::Unordered and Ordering::Implicit. + /// A node's output should be marked Ordering::Unordered if the order is + /// non-deterministic. For example, a hash-join has no predictable output order. + /// + /// If the ordering is Ordering::Implicit then there is a meaningful order but that + /// ordering is not represented by any column in the data. The most common case for + /// this is when reading data from an in-memory table. The data has an implicit "row + /// order" which is not necessarily represented in the data set. + /// + /// A filter or project node will not modify the ordering. Nothing needs to be done + /// other than ensure the index assigned to output batches is the same as the + /// input batch that was mapped. + /// + /// Other nodes may introduce order. For example, an order-by node will emit + /// a brand new ordering independent of the input ordering. + /// + /// Finally, as described above, such as a hash-join or aggregation may may + /// destroy ordering (although these nodes could also choose to establish a + /// new ordering based on the hash keys). + /// + /// Some nodes will require an ordering. For example, a fetch node or an + /// asof join node will only function if the input data is ordered (for fetch + /// it is enough to be implicitly ordered. For an asof join the ordering must + /// be explicit and compatible with the on key.) + /// + /// Nodes that maintain ordering should be careful to avoid introducing gaps + /// in the batch index. This may require emitting empty batches in order to + /// maintain continuity. + virtual const Ordering& ordering() const; + + /// Upstream API: + /// These functions are called by input nodes that want to inform this node + /// about an updated condition (a new input batch or an impending + /// end of stream). + /// + /// Implementation rules: + /// - these may be called anytime after StartProducing() has succeeded + /// (and even during or after StopProducing()) + /// - these may be called concurrently + /// - these are allowed to call back into PauseProducing(), ResumeProducing() + /// and StopProducing() + + /// Transfer input batch to ExecNode + /// + /// A node will typically perform some kind of operation on the batch + /// and then call InputReceived on its outputs with the result. + /// + /// Other nodes may need to accumulate some number of inputs before any + /// output can be produced. These nodes will add the batch to some kind + /// of in-memory accumulation queue and return. + virtual Status InputReceived(ExecNode* input, ExecBatch batch) = 0; + + /// Mark the inputs finished after the given number of batches. + /// + /// This may be called before all inputs are received. This simply fixes + /// the total number of incoming batches for an input, so that the ExecNode + /// knows when it has received all input, regardless of order. + virtual Status InputFinished(ExecNode* input, int total_batches) = 0; + + /// \brief Perform any needed initialization + /// + /// This hook performs any actions in between creation of ExecPlan and the call to + /// StartProducing. An example could be Bloom filter pushdown. The order of ExecNodes + /// that executes this method is undefined, but the calls are made synchronously. + /// + /// At this point a node can rely on all inputs & outputs (and the input schemas) + /// being well defined. + virtual Status Init(); + + /// Lifecycle API: + /// - start / stop to initiate and terminate production + /// - pause / resume to apply backpressure + /// + /// Implementation rules: + /// - StartProducing() should not recurse into the inputs, as it is + /// handled by ExecPlan::StartProducing() + /// - PauseProducing(), ResumeProducing(), StopProducing() may be called + /// concurrently, potentially even before the call to StartProducing + /// has finished. + /// - PauseProducing(), ResumeProducing(), StopProducing() may be called + /// by the downstream nodes' InputReceived(), InputFinished() methods + /// + /// StopProducing may be called due to an error, by the user (e.g. cancel), or + /// because a node has all the data it needs (e.g. limit, top-k on sorted data). + /// This means the method may be called multiple times and we have the following + /// additional rules + /// - StopProducing() must be idempotent + /// - StopProducing() must be forwarded to inputs (this is needed for the limit/top-k + /// case because we may not be stopping the entire plan) + + // Right now, since synchronous calls happen in both directions (input to + // output and then output to input), a node must be careful to be reentrant + // against synchronous calls from its output, *and* also concurrent calls from + // other threads. The most reliable solution is to update the internal state + // first, and notify outputs only at the end. + // + // Concurrent calls to PauseProducing and ResumeProducing can be hard to sequence + // as they may travel at different speeds through the plan. + // + // For example, consider a resume that comes quickly after a pause. If the source + // receives the resume before the pause the source may think the destination is full + // and halt production which would lead to deadlock. + // + // To resolve this a counter is sent for all calls to pause/resume. Only the call with + // the highest counter value is valid. So if a call to PauseProducing(5) comes after + // a call to ResumeProducing(6) then the source should continue producing. + + /// \brief Start producing + /// + /// This must only be called once. + /// + /// This is typically called automatically by ExecPlan::StartProducing(). + virtual Status StartProducing() = 0; + + /// \brief Pause producing temporarily + /// + /// \param output Pointer to the output that is full + /// \param counter Counter used to sequence calls to pause/resume + /// + /// This call is a hint that an output node is currently not willing + /// to receive data. + /// + /// This may be called any number of times. + /// However, the node is still free to produce data (which may be difficult + /// to prevent anyway if data is produced using multiple threads). + virtual void PauseProducing(ExecNode* output, int32_t counter) = 0; + + /// \brief Resume producing after a temporary pause + /// + /// \param output Pointer to the output that is now free + /// \param counter Counter used to sequence calls to pause/resume + /// + /// This call is a hint that an output node is willing to receive data again. + /// + /// This may be called any number of times. + virtual void ResumeProducing(ExecNode* output, int32_t counter) = 0; + + /// \brief Stop producing new data + /// + /// If this node is a source then the source should stop generating data + /// as quickly as possible. If this node is not a source then there is typically + /// nothing that needs to be done although a node may choose to start ignoring incoming + /// data. + /// + /// This method will be called when an error occurs in the plan + /// This method may also be called by the user if they wish to end a plan early + /// Finally, this method may be called if a node determines it no longer needs any more + /// input (for example, a limit node). + /// + /// This method may be called multiple times. + /// + /// This is not a pause. There will be no way to start the source again after this has + /// been called. + virtual Status StopProducing(); + + std::string ToString(int indent = 0) const; + + protected: + ExecNode(ExecPlan* plan, NodeVector inputs, std::vector input_labels, + std::shared_ptr output_schema); + + virtual Status StopProducingImpl() = 0; + + /// Provide extra info to include in the string representation. + virtual std::string ToStringExtra(int indent = 0) const; + + std::atomic stopped_; + ExecPlan* plan_; + std::string label_; + + NodeVector inputs_; + std::vector input_labels_; + + std::shared_ptr output_schema_; + ExecNode* output_ = NULLPTR; +}; + +/// \brief An extensible registry for factories of ExecNodes +class ARROW_ACERO_EXPORT ExecFactoryRegistry { + public: + using Factory = std::function(ExecPlan*, std::vector, + const ExecNodeOptions&)>; + + virtual ~ExecFactoryRegistry() = default; + + /// \brief Get the named factory from this registry + /// + /// will raise if factory_name is not found + virtual Result GetFactory(const std::string& factory_name) = 0; + + /// \brief Add a factory to this registry with the provided name + /// + /// will raise if factory_name is already in the registry + virtual Status AddFactory(std::string factory_name, Factory factory) = 0; +}; + +/// The default registry, which includes built-in factories. +ARROW_ACERO_EXPORT +ExecFactoryRegistry* default_exec_factory_registry(); + +/// \brief Construct an ExecNode using the named factory +inline Result MakeExecNode( + const std::string& factory_name, ExecPlan* plan, std::vector inputs, + const ExecNodeOptions& options, + ExecFactoryRegistry* registry = default_exec_factory_registry()) { + ARROW_ASSIGN_OR_RAISE(auto factory, registry->GetFactory(factory_name)); + return factory(plan, std::move(inputs), options); +} + +/// @} + +/// \addtogroup acero-api +/// @{ + +/// \brief Helper class for declaring execution nodes +/// +/// A Declaration represents an unconstructed ExecNode (and potentially an entire graph +/// since its inputs may also be Declarations) +/// +/// A Declaration can be converted to a plan and executed using one of the +/// DeclarationToXyz methods. +/// +/// For more direct control, a Declaration can be added to an existing execution +/// plan with Declaration::AddToPlan, which will recursively construct any inputs as +/// necessary. +struct ARROW_ACERO_EXPORT Declaration { + using Input = std::variant; + + Declaration() {} + + /// \brief construct a declaration + /// \param factory_name the name of the exec node to construct. The node must have + /// been added to the exec node registry with this name. + /// \param inputs the inputs to the node, these should be other declarations + /// \param options options that control the behavior of the node. You must use + /// the appropriate subclass. For example, if `factory_name` is + /// "project" then `options` should be ProjectNodeOptions. + /// \param label a label to give the node. Can be used to distinguish it from other + /// nodes of the same type in the plan. + Declaration(std::string factory_name, std::vector inputs, + std::shared_ptr options, std::string label) + : factory_name{std::move(factory_name)}, + inputs{std::move(inputs)}, + options{std::move(options)}, + label{std::move(label)} {} + + template + Declaration(std::string factory_name, std::vector inputs, Options options, + std::string label) + : Declaration{std::move(factory_name), std::move(inputs), + std::shared_ptr( + std::make_shared(std::move(options))), + std::move(label)} {} + + template + Declaration(std::string factory_name, std::vector inputs, Options options) + : Declaration{std::move(factory_name), std::move(inputs), std::move(options), + /*label=*/""} {} + + template + Declaration(std::string factory_name, Options options) + : Declaration{std::move(factory_name), {}, std::move(options), /*label=*/""} {} + + template + Declaration(std::string factory_name, Options options, std::string label) + : Declaration{std::move(factory_name), {}, std::move(options), std::move(label)} {} + + /// \brief Convenience factory for the common case of a simple sequence of nodes. + /// + /// Each of decls will be appended to the inputs of the subsequent declaration, + /// and the final modified declaration will be returned. + /// + /// Without this convenience factory, constructing a sequence would require explicit, + /// difficult-to-read nesting: + /// + /// Declaration{"n3", + /// { + /// Declaration{"n2", + /// { + /// Declaration{"n1", + /// { + /// Declaration{"n0", N0Opts{}}, + /// }, + /// N1Opts{}}, + /// }, + /// N2Opts{}}, + /// }, + /// N3Opts{}}; + /// + /// An equivalent Declaration can be constructed more tersely using Sequence: + /// + /// Declaration::Sequence({ + /// {"n0", N0Opts{}}, + /// {"n1", N1Opts{}}, + /// {"n2", N2Opts{}}, + /// {"n3", N3Opts{}}, + /// }); + static Declaration Sequence(std::vector decls); + + /// \brief add the declaration to an already created execution plan + /// \param plan the plan to add the node to + /// \param registry the registry to use to lookup the node factory + /// + /// This method will recursively call AddToPlan on all of the declaration's inputs. + /// This method is only for advanced use when the DeclarationToXyz methods are not + /// sufficient. + /// + /// \return the instantiated execution node + Result AddToPlan(ExecPlan* plan, ExecFactoryRegistry* registry = + default_exec_factory_registry()) const; + + // Validate a declaration + bool IsValid(ExecFactoryRegistry* registry = default_exec_factory_registry()) const; + + /// \brief the name of the factory to use when creating a node + std::string factory_name; + /// \brief the declarations's inputs + std::vector inputs; + /// \brief options to control the behavior of the node + std::shared_ptr options; + /// \brief a label to give the node in the plan + std::string label; +}; + +/// \brief How to handle unaligned buffers +enum class UnalignedBufferHandling { kWarn, kIgnore, kReallocate, kError }; + +/// \brief get the default behavior of unaligned buffer handling +/// +/// This is configurable via the ACERO_ALIGNMENT_HANDLING environment variable which +/// can be set to "warn", "ignore", "reallocate", or "error". If the environment +/// variable is not set, or is set to an invalid value, this will return kWarn +UnalignedBufferHandling GetDefaultUnalignedBufferHandling(); + +/// \brief plan-wide options that can be specified when executing an execution plan +struct ARROW_ACERO_EXPORT QueryOptions { + /// \brief Should the plan use a legacy batching strategy + /// + /// This is currently in place only to support the Scanner::ToTable + /// method. This method relies on batch indices from the scanner + /// remaining consistent. This is impractical in the ExecPlan which + /// might slice batches as needed (e.g. for a join) + /// + /// However, it still works for simple plans and this is the only way + /// we have at the moment for maintaining implicit order. + bool use_legacy_batching = false; + + /// If the output has a meaningful order then sequence the output of the plan + /// + /// The default behavior (std::nullopt) will sequence output batches if there + /// is a meaningful ordering in the final node and will emit batches immediately + /// otherwise. + /// + /// If explicitly set to true then plan execution will fail if there is no + /// meaningful ordering. This can be useful to validate a query that should + /// be emitting ordered results. + /// + /// If explicitly set to false then batches will be emit immediately even if there + /// is a meaningful ordering. This could cause batches to be emit out of order but + /// may offer a small decrease to latency. + std::optional sequence_output = std::nullopt; + + /// \brief should the plan use multiple background threads for CPU-intensive work + /// + /// If this is false then all CPU work will be done on the calling thread. I/O tasks + /// will still happen on the I/O executor and may be multi-threaded (but should not use + /// significant CPU resources). + /// + /// Will be ignored if custom_cpu_executor is set + bool use_threads = true; + + /// \brief custom executor to use for CPU-intensive work + /// + /// Must be null or remain valid for the duration of the plan. If this is null then + /// a default thread pool will be chosen whose behavior will be controlled by + /// the `use_threads` option. + ::arrow::internal::Executor* custom_cpu_executor = NULLPTR; + + /// \brief custom executor to use for IO work + /// + /// Must be null or remain valid for the duration of the plan. If this is null then + /// the global io thread pool will be chosen whose behavior will be controlled by + /// the "ARROW_IO_THREADS" environment. + ::arrow::internal::Executor* custom_io_executor = NULLPTR; + + /// \brief a memory pool to use for allocations + /// + /// Must remain valid for the duration of the plan. + MemoryPool* memory_pool = default_memory_pool(); + + /// \brief a function registry to use for the plan + /// + /// Must remain valid for the duration of the plan. + FunctionRegistry* function_registry = GetFunctionRegistry(); + /// \brief the names of the output columns + /// + /// If this is empty then names will be generated based on the input columns + /// + /// If set then the number of names must equal the number of output columns + std::vector field_names; + + /// \brief Policy for unaligned buffers in source data + /// + /// Various compute functions and acero internals will type pun array + /// buffers from uint8_t* to some kind of value type (e.g. we might + /// cast to int32_t* to add two int32 arrays) + /// + /// If the buffer is poorly aligned (e.g. an int32 array is not aligned + /// on a 4-byte boundary) then this is technically undefined behavior in C++. + /// However, most modern compilers and CPUs are fairly tolerant of this + /// behavior and nothing bad (beyond a small hit to performance) is likely + /// to happen. + /// + /// Note that this only applies to source buffers. All buffers allocated internally + /// by Acero will be suitably aligned. + /// + /// If this field is set to kWarn then Acero will check if any buffers are unaligned + /// and, if they are, will emit a warning. + /// + /// If this field is set to kReallocate then Acero will allocate a new, suitably aligned + /// buffer and copy the contents from the old buffer into this new buffer. + /// + /// If this field is set to kError then Acero will gracefully abort the plan instead. + /// + /// If this field is set to kIgnore then Acero will not even check if the buffers are + /// unaligned. + /// + /// If this field is not set then it will be treated as kWarn unless overridden + /// by the ACERO_ALIGNMENT_HANDLING environment variable + std::optional unaligned_buffer_handling; +}; + +/// \brief Calculate the output schema of a declaration +/// +/// This does not actually execute the plan. This operation may fail if the +/// declaration represents an invalid plan (e.g. a project node with multiple inputs) +/// +/// \param declaration A declaration describing an execution plan +/// \param function_registry The function registry to use for function execution. If null +/// then the default function registry will be used. +/// +/// \return the schema that batches would have after going through the execution plan +ARROW_ACERO_EXPORT Result> DeclarationToSchema( + const Declaration& declaration, FunctionRegistry* function_registry = NULLPTR); + +/// \brief Create a string representation of a plan +/// +/// This representation is for debug purposes only. +/// +/// Conversion to a string may fail if the declaration represents an +/// invalid plan. +/// +/// Use Substrait for complete serialization of plans +/// +/// \param declaration A declaration describing an execution plan +/// \param function_registry The function registry to use for function execution. If null +/// then the default function registry will be used. +/// +/// \return a string representation of the plan suitable for debugging output +ARROW_ACERO_EXPORT Result DeclarationToString( + const Declaration& declaration, FunctionRegistry* function_registry = NULLPTR); + +/// \brief Utility method to run a declaration and collect the results into a table +/// +/// \param declaration A declaration describing the plan to run +/// \param use_threads If `use_threads` is false then all CPU work will be done on the +/// calling thread. I/O tasks will still happen on the I/O executor +/// and may be multi-threaded (but should not use significant CPU +/// resources). +/// \param memory_pool The memory pool to use for allocations made while running the plan. +/// \param function_registry The function registry to use for function execution. If null +/// then the default function registry will be used. +/// +/// This method will add a sink node to the declaration to collect results into a +/// table. It will then create an ExecPlan from the declaration, start the exec plan, +/// block until the plan has finished, and return the created table. +ARROW_ACERO_EXPORT Result> DeclarationToTable( + Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +ARROW_ACERO_EXPORT Result> DeclarationToTable( + Declaration declaration, QueryOptions query_options); + +/// \brief Asynchronous version of \see DeclarationToTable +/// +/// \param declaration A declaration describing the plan to run +/// \param use_threads The behavior of use_threads is slightly different than the +/// synchronous version since we cannot run synchronously on the +/// calling thread. Instead, if use_threads=false then a new thread +/// pool will be created with a single thread and this will be used for +/// all compute work. +/// \param memory_pool The memory pool to use for allocations made while running the plan. +/// \param function_registry The function registry to use for function execution. If null +/// then the default function registry will be used. +ARROW_ACERO_EXPORT Future> DeclarationToTableAsync( + Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +/// \brief Overload of \see DeclarationToTableAsync accepting a custom exec context +/// +/// The executor must be specified (cannot be null) and must be kept alive until the +/// returned future finishes. +ARROW_ACERO_EXPORT Future> DeclarationToTableAsync( + Declaration declaration, ExecContext custom_exec_context); + +/// \brief a collection of exec batches with a common schema +struct BatchesWithCommonSchema { + std::vector batches; + std::shared_ptr schema; +}; + +/// \brief Utility method to run a declaration and collect the results into ExecBatch +/// vector +/// +/// \see DeclarationToTable for details on threading & execution +ARROW_ACERO_EXPORT Result DeclarationToExecBatches( + Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +ARROW_ACERO_EXPORT Result DeclarationToExecBatches( + Declaration declaration, QueryOptions query_options); + +/// \brief Asynchronous version of \see DeclarationToExecBatches +/// +/// \see DeclarationToTableAsync for details on threading & execution +ARROW_ACERO_EXPORT Future DeclarationToExecBatchesAsync( + Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +/// \brief Overload of \see DeclarationToExecBatchesAsync accepting a custom exec context +/// +/// \see DeclarationToTableAsync for details on threading & execution +ARROW_ACERO_EXPORT Future DeclarationToExecBatchesAsync( + Declaration declaration, ExecContext custom_exec_context); + +/// \brief Utility method to run a declaration and collect the results into a vector +/// +/// \see DeclarationToTable for details on threading & execution +ARROW_ACERO_EXPORT Result>> DeclarationToBatches( + Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +ARROW_ACERO_EXPORT Result>> DeclarationToBatches( + Declaration declaration, QueryOptions query_options); + +/// \brief Asynchronous version of \see DeclarationToBatches +/// +/// \see DeclarationToTableAsync for details on threading & execution +ARROW_ACERO_EXPORT Future>> +DeclarationToBatchesAsync(Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +/// \brief Overload of \see DeclarationToBatchesAsync accepting a custom exec context +/// +/// \see DeclarationToTableAsync for details on threading & execution +ARROW_ACERO_EXPORT Future>> +DeclarationToBatchesAsync(Declaration declaration, ExecContext exec_context); + +/// \brief Utility method to run a declaration and return results as a RecordBatchReader +/// +/// If an exec context is not provided then a default exec context will be used based +/// on the value of `use_threads`. If `use_threads` is false then the CPU executor will +/// be a serial executor and all CPU work will be done on the calling thread. I/O tasks +/// will still happen on the I/O executor and may be multi-threaded. +/// +/// If `use_threads` is false then all CPU work will happen during the calls to +/// RecordBatchReader::Next and no CPU work will happen in the background. If +/// `use_threads` is true then CPU work will happen on the CPU thread pool and tasks may +/// run in between calls to RecordBatchReader::Next. If the returned reader is not +/// consumed quickly enough then the plan will eventually pause as the backpressure queue +/// fills up. +/// +/// If a custom exec context is provided then the value of `use_threads` will be ignored. +/// +/// The returned RecordBatchReader can be closed early to cancel the computation of record +/// batches. In this case, only errors encountered by the computation may be reported. In +/// particular, no cancellation error may be reported. +ARROW_ACERO_EXPORT Result> DeclarationToReader( + Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +ARROW_ACERO_EXPORT Result> DeclarationToReader( + Declaration declaration, QueryOptions query_options); + +/// \brief Utility method to run a declaration and ignore results +/// +/// This can be useful when the data are consumed as part of the plan itself, for +/// example, when the plan ends with a write node. +/// +/// \see DeclarationToTable for details on threading & execution +ARROW_ACERO_EXPORT Status +DeclarationToStatus(Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +ARROW_ACERO_EXPORT Status DeclarationToStatus(Declaration declaration, + QueryOptions query_options); + +/// \brief Asynchronous version of \see DeclarationToStatus +/// +/// This can be useful when the data are consumed as part of the plan itself, for +/// example, when the plan ends with a write node. +/// +/// \see DeclarationToTableAsync for details on threading & execution +ARROW_ACERO_EXPORT Future<> DeclarationToStatusAsync( + Declaration declaration, bool use_threads = true, + MemoryPool* memory_pool = default_memory_pool(), + FunctionRegistry* function_registry = NULLPTR); + +/// \brief Overload of \see DeclarationToStatusAsync accepting a custom exec context +/// +/// \see DeclarationToTableAsync for details on threading & execution +ARROW_ACERO_EXPORT Future<> DeclarationToStatusAsync(Declaration declaration, + ExecContext exec_context); + +/// @} + +/// \brief Wrap an ExecBatch generator in a RecordBatchReader. +/// +/// The RecordBatchReader does not impose any ordering on emitted batches. +ARROW_ACERO_EXPORT +std::shared_ptr MakeGeneratorReader( + std::shared_ptr, std::function>()>, + MemoryPool*); + +constexpr int kDefaultBackgroundMaxQ = 32; +constexpr int kDefaultBackgroundQRestart = 16; + +/// \brief Make a generator of RecordBatchReaders +/// +/// Useful as a source node for an Exec plan +ARROW_ACERO_EXPORT +Result>()>> MakeReaderGenerator( + std::shared_ptr reader, arrow::internal::Executor* io_executor, + int max_q = kDefaultBackgroundMaxQ, int q_restart = kDefaultBackgroundQRestart); + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join.h new file mode 100644 index 0000000000000000000000000000000000000000..c0faacf04baf02e865a61a0301a0cfa92b3fab1b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join.h @@ -0,0 +1,75 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/acero/accumulation_queue.h" +#include "arrow/acero/bloom_filter.h" +#include "arrow/acero/options.h" +#include "arrow/acero/query_context.h" +#include "arrow/acero/schema_util.h" +#include "arrow/acero/task_util.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/tracing.h" + +namespace arrow { +namespace acero { + +using util::AccumulationQueue; + +class ARROW_ACERO_EXPORT HashJoinImpl { + public: + using OutputBatchCallback = std::function; + using BuildFinishedCallback = std::function; + using FinishedCallback = std::function; + using RegisterTaskGroupCallback = std::function, std::function)>; + using StartTaskGroupCallback = std::function; + using AbortContinuationImpl = std::function; + + virtual ~HashJoinImpl() = default; + virtual Status Init(QueryContext* ctx, JoinType join_type, size_t num_threads, + const HashJoinProjectionMaps* proj_map_left, + const HashJoinProjectionMaps* proj_map_right, + std::vector key_cmp, Expression filter, + RegisterTaskGroupCallback register_task_group_callback, + StartTaskGroupCallback start_task_group_callback, + OutputBatchCallback output_batch_callback, + FinishedCallback finished_callback) = 0; + + virtual Status BuildHashTable(size_t thread_index, AccumulationQueue batches, + BuildFinishedCallback on_finished) = 0; + virtual Status ProbeSingleBatch(size_t thread_index, ExecBatch batch) = 0; + virtual Status ProbingFinished(size_t thread_index) = 0; + virtual void Abort(TaskScheduler::AbortContinuationImpl pos_abort_callback) = 0; + virtual std::string ToString() const = 0; + + static Result> MakeBasic(); + static Result> MakeSwiss(); + + protected: + arrow::util::tracing::Span span_; +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join_dict.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join_dict.h new file mode 100644 index 0000000000000000000000000000000000000000..02454a7146278176e27379e6033f79547574a367 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join_dict.h @@ -0,0 +1,318 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/acero/schema_util.h" +#include "arrow/compute/exec.h" +#include "arrow/compute/row/row_encoder_internal.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" + +// This file contains hash join logic related to handling of dictionary encoded key +// columns. +// +// A key column from probe side of the join can be matched against a key column from build +// side of the join, as long as the underlying value types are equal. That means that: +// - both scalars and arrays can be used and even mixed in the same column +// - dictionary column can be matched against non-dictionary column if underlying value +// types are equal +// - dictionary column can be matched against dictionary column with a different index +// type, and potentially using a different dictionary, if underlying value types are equal +// +// We currently require in hash join that for all dictionary encoded columns, the same +// dictionary is used in all input exec batches. +// +// In order to allow matching columns with different dictionaries, different dictionary +// index types, and dictionary key against non-dictionary key, internally comparisons will +// be evaluated after remapping values on both sides of the join to a common +// representation (which will be called "unified representation"). This common +// representation is a column of int32() type (not a dictionary column). It represents an +// index in the unified dictionary computed for the (only) dictionary present on build +// side (an empty dictionary is still created for an empty build side). Null value is +// always represented in this common representation as null int32 value, unified +// dictionary will never contain a null value (so there is no ambiguity of representing +// nulls as either index to a null entry in the dictionary or null index). +// +// Unified dictionary represents values present on build side. There may be values on +// probe side that are not present in it. All such values, that are not null, are mapped +// in the common representation to a special constant kMissingValueId. +// + +namespace arrow { + +using compute::ExecBatch; +using compute::ExecContext; +using compute::internal::RowEncoder; + +namespace acero { + +/// Helper class with operations that are stateless and common to processing of dictionary +/// keys on both build and probe side. +class HashJoinDictUtil { + public: + // Null values in unified representation are always represented as null that has + // corresponding integer set to this constant + static constexpr int32_t kNullId = 0; + // Constant representing a value, that is not null, missing on the build side, in + // unified representation. + static constexpr int32_t kMissingValueId = -1; + + // Check if data types of corresponding pair of key column on build and probe side are + // compatible + static bool KeyDataTypesValid(const std::shared_ptr& probe_data_type, + const std::shared_ptr& build_data_type); + + // Input must be dictionary array or dictionary scalar. + // A precomputed and provided here lookup table in the form of int32() array will be + // used to remap input indices to unified representation. + // + static Result> IndexRemapUsingLUT( + ExecContext* ctx, const Datum& indices, int64_t batch_length, + const std::shared_ptr& map_array, + const std::shared_ptr& data_type); + + // Return int32() array that contains indices of input dictionary array or scalar after + // type casting. + static Result> ConvertToInt32( + const std::shared_ptr& from_type, const Datum& input, + int64_t batch_length, ExecContext* ctx); + + // Return an array that contains elements of input int32() array after casting to a + // given integer type. This is used for mapping unified representation stored in the + // hash table on build side back to original input data type of hash join, when + // outputting hash join results to parent exec node. + // + static Result> ConvertFromInt32( + const std::shared_ptr& to_type, const Datum& input, int64_t batch_length, + ExecContext* ctx); + + // Return dictionary referenced in either dictionary array or dictionary scalar + static std::shared_ptr ExtractDictionary(const Datum& data); +}; + +/// Implements processing of dictionary arrays/scalars in key columns on the build side of +/// a hash join. +/// Each instance of this class corresponds to a single column and stores and +/// processes only the information related to that column. +/// Const methods are thread-safe, non-const methods are not (the caller must make sure +/// that only one thread at any time will access them). +/// +class HashJoinDictBuild { + public: + // Returns true if the key column (described in input by its data type) requires any + // pre- or post-processing related to handling dictionaries. + // + static bool KeyNeedsProcessing(const std::shared_ptr& build_data_type) { + return (build_data_type->id() == Type::DICTIONARY); + } + + // Data type of unified representation + static std::shared_ptr DataTypeAfterRemapping() { return int32(); } + + // Should be called only once in hash join, before processing any build or probe + // batches. + // + // Takes a pointer to the dictionary for a corresponding key column on the build side as + // an input. If the build side is empty, it still needs to be called, but with + // dictionary pointer set to null. + // + // Currently it is required that all input batches on build side share the same + // dictionary. For each input batch during its pre-processing, dictionary will be + // checked and error will be returned if it is different then the one provided in the + // call to this method. + // + // Unifies the dictionary. The order of the values is still preserved. + // Null and duplicate entries are removed. If the dictionary is already unified, its + // copy will be produced and stored within this class. + // + // Prepares the mapping from ids within original dictionary to the ids in the resulting + // dictionary. This is used later on to pre-process (map to unified representation) key + // column on build side. + // + // Prepares the reverse mapping (in the form of hash table) from values to the ids in + // the resulting dictionary. This will be used later on to pre-process (map to unified + // representation) key column on probe side. Values on probe side that are not present + // in the original dictionary will be mapped to a special constant kMissingValueId. The + // exception is made for nulls, which get always mapped to nulls (both when null is + // represented as a dictionary id pointing to a null and a null dictionary id). + // + Status Init(ExecContext* ctx, std::shared_ptr dictionary, + std::shared_ptr index_type, std::shared_ptr value_type); + + // Remap array or scalar values into unified representation (array of int32()). + // Outputs kMissingValueId if input value is not found in the unified dictionary. + // Outputs null for null input value (with corresponding data set to kNullId). + // + Result> RemapInputValues(ExecContext* ctx, + const Datum& values, + int64_t batch_length) const; + + // Remap dictionary array or dictionary scalar on build side to unified representation. + // Dictionary referenced in the input must match the dictionary that was + // given during initialization. + // The output is a dictionary array that references unified dictionary. + // + Result> RemapInput( + ExecContext* ctx, const Datum& indices, int64_t batch_length, + const std::shared_ptr& data_type) const; + + // Outputs dictionary array referencing unified dictionary, given an array with 32-bit + // ids. + // Used to post-process values looked up in a hash table on build side of the hash join + // before outputting to the parent exec node. + // + Result> RemapOutput(const ArrayData& indices32Bit, + ExecContext* ctx) const; + + // Release shared pointers and memory + void CleanUp(); + + private: + // Data type of dictionary ids for the input dictionary on build side + std::shared_ptr index_type_; + // Data type of values for the input dictionary on build side + std::shared_ptr value_type_; + // Mapping from (encoded as string) values to the ids in unified dictionary + std::unordered_map hash_table_; + // Mapping from input dictionary ids to unified dictionary ids + std::shared_ptr remapped_ids_; + // Input dictionary + std::shared_ptr dictionary_; + // Unified dictionary + std::shared_ptr unified_dictionary_; +}; + +/// Implements processing of dictionary arrays/scalars in key columns on the probe side of +/// a hash join. +/// Each instance of this class corresponds to a single column and stores and +/// processes only the information related to that column. +/// It is not thread-safe - every participating thread should use its own instance of +/// this class. +/// +class HashJoinDictProbe { + public: + static bool KeyNeedsProcessing(const std::shared_ptr& probe_data_type, + const std::shared_ptr& build_data_type); + + // Data type of the result of remapping input key column. + // + // The result of remapping is what is used in hash join for matching keys on build and + // probe side. The exact data types may be different, as described below, and therefore + // a common representation is needed for simplifying comparisons of pairs of keys on + // both sides. + // + // We support matching key that is of non-dictionary type with key that is of dictionary + // type, as long as the underlying value types are equal. We support matching when both + // keys are of dictionary type, regardless whether underlying dictionary index types are + // the same or not. + // + static std::shared_ptr DataTypeAfterRemapping( + const std::shared_ptr& build_data_type); + + // Should only be called if KeyNeedsProcessing method returns true for a pair of + // corresponding key columns from build and probe side. + // Converts values in order to match the common representation for + // both build and probe side used in hash table comparison. + // Supports arrays and scalars as input. + // Argument opt_build_side should be null if dictionary key on probe side is matched + // with non-dictionary key on build side. + // + Result> RemapInput( + const HashJoinDictBuild* opt_build_side, const Datum& data, int64_t batch_length, + const std::shared_ptr& probe_data_type, + const std::shared_ptr& build_data_type, ExecContext* ctx); + + void CleanUp(); + + private: + // May be null if probe side key is non-dictionary. Otherwise it is used to verify that + // only a single dictionary is referenced in exec batch on probe side of hash join. + std::shared_ptr dictionary_; + // Mapping from dictionary on probe side of hash join (if it is used) to unified + // representation. + std::shared_ptr remapped_ids_; + // Encoder of key columns that uses unified representation instead of original data type + // for key columns that need to use it (have dictionaries on either side of the join). + RowEncoder encoder_; +}; + +// Encapsulates dictionary handling logic for build side of hash join. +// +class HashJoinDictBuildMulti { + public: + Status Init(const SchemaProjectionMaps& proj_map, + const ExecBatch* opt_non_empty_batch, ExecContext* ctx); + static void InitEncoder(const SchemaProjectionMaps& proj_map, + RowEncoder* encoder, ExecContext* ctx); + Status EncodeBatch(size_t thread_index, + const SchemaProjectionMaps& proj_map, + const ExecBatch& batch, RowEncoder* encoder, ExecContext* ctx) const; + Status PostDecode(const SchemaProjectionMaps& proj_map, + ExecBatch* decoded_key_batch, ExecContext* ctx); + const HashJoinDictBuild& get_dict_build(int icol) const { return remap_imp_[icol]; } + + private: + std::vector needs_remap_; + std::vector remap_imp_; +}; + +// Encapsulates dictionary handling logic for probe side of hash join +// +class HashJoinDictProbeMulti { + public: + void Init(size_t num_threads); + bool BatchRemapNeeded(size_t thread_index, + const SchemaProjectionMaps& proj_map_probe, + const SchemaProjectionMaps& proj_map_build, + ExecContext* ctx); + Status EncodeBatch(size_t thread_index, + const SchemaProjectionMaps& proj_map_probe, + const SchemaProjectionMaps& proj_map_build, + const HashJoinDictBuildMulti& dict_build, const ExecBatch& batch, + RowEncoder** out_encoder, ExecBatch* opt_out_key_batch, + ExecContext* ctx); + + private: + void InitLocalStateIfNeeded( + size_t thread_index, const SchemaProjectionMaps& proj_map_probe, + const SchemaProjectionMaps& proj_map_build, ExecContext* ctx); + static void InitEncoder(const SchemaProjectionMaps& proj_map_probe, + const SchemaProjectionMaps& proj_map_build, + RowEncoder* encoder, ExecContext* ctx); + struct ThreadLocalState { + bool is_initialized; + // Whether any key column needs remapping (because of dictionaries used) before doing + // join hash table lookups + bool any_needs_remap; + // Whether each key column needs remapping before doing join hash table lookups + std::vector needs_remap; + std::vector remap_imp; + // Encoder of key columns that uses unified representation instead of original data + // type for key columns that need to use it (have dictionaries on either side of the + // join). + RowEncoder post_remap_encoder; + }; + std::vector local_states_; +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join_node.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join_node.h new file mode 100644 index 0000000000000000000000000000000000000000..19745b8675cf0c63ed92c6e5448c9e6a68467f59 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/hash_join_node.h @@ -0,0 +1,103 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/acero/options.h" +#include "arrow/acero/schema_util.h" +#include "arrow/result.h" +#include "arrow/status.h" + +namespace arrow { + +using compute::ExecContext; + +namespace acero { + +class ARROW_ACERO_EXPORT HashJoinSchema { + public: + Status Init(JoinType join_type, const Schema& left_schema, + const std::vector& left_keys, const Schema& right_schema, + const std::vector& right_keys, const Expression& filter, + const std::string& left_field_name_prefix, + const std::string& right_field_name_prefix); + + Status Init(JoinType join_type, const Schema& left_schema, + const std::vector& left_keys, + const std::vector& left_output, const Schema& right_schema, + const std::vector& right_keys, + const std::vector& right_output, const Expression& filter, + const std::string& left_field_name_prefix, + const std::string& right_field_name_prefix); + + static Status ValidateSchemas(JoinType join_type, const Schema& left_schema, + const std::vector& left_keys, + const std::vector& left_output, + const Schema& right_schema, + const std::vector& right_keys, + const std::vector& right_output, + const std::string& left_field_name_prefix, + const std::string& right_field_name_prefix); + + bool HasDictionaries() const; + + bool HasLargeBinary() const; + + Result BindFilter(Expression filter, const Schema& left_schema, + const Schema& right_schema, ExecContext* exec_context); + std::shared_ptr MakeOutputSchema(const std::string& left_field_name_suffix, + const std::string& right_field_name_suffix); + + bool LeftPayloadIsEmpty() const { return PayloadIsEmpty(0); } + + bool RightPayloadIsEmpty() const { return PayloadIsEmpty(1); } + + static int kMissingField() { + return SchemaProjectionMaps::kMissingField; + } + + SchemaProjectionMaps proj_maps[2]; + + private: + static bool IsTypeSupported(const DataType& type); + + Status CollectFilterColumns(std::vector& left_filter, + std::vector& right_filter, + const Expression& filter, const Schema& left_schema, + const Schema& right_schema); + + Expression RewriteFilterToUseFilterSchema(int right_filter_offset, + const SchemaProjectionMap& left_to_filter, + const SchemaProjectionMap& right_to_filter, + const Expression& filter); + + bool PayloadIsEmpty(int side) const { + assert(side == 0 || side == 1); + return proj_maps[side].num_cols(HashJoinProjection::PAYLOAD) == 0; + } + + static Result> ComputePayload(const Schema& schema, + const std::vector& output, + const std::vector& filter, + const std::vector& key); +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/map_node.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/map_node.h new file mode 100644 index 0000000000000000000000000000000000000000..8bdd0ab2ca3854c6561aa3735ae143e7c58b4f77 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/map_node.h @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/acero/exec_plan.h" +#include "arrow/acero/util.h" +#include "arrow/acero/visibility.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/cancel.h" +#include "arrow/util/type_fwd.h" + +namespace arrow { +namespace acero { + +/// A utility base class for simple exec nodes with one input +/// +/// Pause/Resume Producing are forwarded appropriately +/// There is nothing to do in StopProducingImpl +/// +/// An AtomicCounter is used to keep track of when all data has arrived. When it +/// has the Finish() method will be invoked +class ARROW_ACERO_EXPORT MapNode : public ExecNode, public TracedNode { + public: + MapNode(ExecPlan* plan, std::vector inputs, + std::shared_ptr output_schema); + + Status InputFinished(ExecNode* input, int total_batches) override; + + Status StartProducing() override; + + void PauseProducing(ExecNode* output, int32_t counter) override; + + void ResumeProducing(ExecNode* output, int32_t counter) override; + + Status InputReceived(ExecNode* input, ExecBatch batch) override; + + const Ordering& ordering() const override; + + protected: + Status StopProducingImpl() override; + + /// Transform a batch + /// + /// The output batch will have the same guarantee as the input batch + /// If this was the last batch this call may trigger Finish() + virtual Result ProcessBatch(ExecBatch batch) = 0; + + /// Function called after all data has been received + /// + /// By default this does nothing. Override this to provide a custom implementation. + virtual void Finish(); + + protected: + // Counter for the number of batches received + AtomicCounter input_counter_; +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/options.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/options.h new file mode 100644 index 0000000000000000000000000000000000000000..827e9ea775d7b8e892d05f9b81a79ec25991cc3c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/options.h @@ -0,0 +1,874 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/acero/type_fwd.h" +#include "arrow/acero/visibility.h" +#include "arrow/compute/api_aggregate.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/exec.h" +#include "arrow/compute/expression.h" +#include "arrow/result.h" +#include "arrow/util/future.h" + +namespace arrow { + +using compute::Aggregate; +using compute::ExecBatch; +using compute::Expression; +using compute::literal; +using compute::Ordering; +using compute::SelectKOptions; +using compute::SortOptions; + +namespace internal { + +class Executor; + +} // namespace internal + +namespace acero { + +/// \brief This must not be used in release-mode +struct DebugOptions; + +using AsyncExecBatchGenerator = std::function>()>; + +/// \addtogroup acero-nodes +/// @{ + +/// \brief A base class for all options objects +/// +/// The only time this is used directly is when a node has no configuration +class ARROW_ACERO_EXPORT ExecNodeOptions { + public: + virtual ~ExecNodeOptions() = default; + + /// \brief This must not be used in release-mode + std::shared_ptr debug_opts; +}; + +/// \brief A node representing a generic source of data for Acero +/// +/// The source node will start calling `generator` during StartProducing. An initial +/// task will be created that will call `generator`. It will not call `generator` +/// reentrantly. If the source can be read in parallel then those details should be +/// encapsulated within `generator`. +/// +/// For each batch received a new task will be created to push that batch downstream. +/// This task will slice smaller units of size `ExecPlan::kMaxBatchSize` from the +/// parent batch and call InputReceived. Thus, if the `generator` yields a large +/// batch it may result in several calls to InputReceived. +/// +/// The SourceNode will, by default, assign an implicit ordering to outgoing batches. +/// This is valid as long as the generator generates batches in a deterministic fashion. +/// Currently, the only way to override this is to subclass the SourceNode. +/// +/// This node is not generally used directly but can serve as the basis for various +/// specialized nodes. +class ARROW_ACERO_EXPORT SourceNodeOptions : public ExecNodeOptions { + public: + /// Create an instance from values + SourceNodeOptions(std::shared_ptr output_schema, + std::function>()> generator, + Ordering ordering = Ordering::Unordered()) + : output_schema(std::move(output_schema)), + generator(std::move(generator)), + ordering(std::move(ordering)) {} + + /// \brief the schema for batches that will be generated by this source + std::shared_ptr output_schema; + /// \brief an asynchronous stream of batches ending with std::nullopt + std::function>()> generator; + /// \brief the order of the data, defaults to Ordering::Unordered + Ordering ordering; +}; + +/// \brief a node that generates data from a table already loaded in memory +/// +/// The table source node will slice off chunks, defined by `max_batch_size` +/// for parallel processing. The table source node extends source node and so these +/// chunks will be iteratively processed in small batches. \see SourceNodeOptions +/// for details. +class ARROW_ACERO_EXPORT TableSourceNodeOptions : public ExecNodeOptions { + public: + static constexpr int64_t kDefaultMaxBatchSize = 1 << 20; + + /// Create an instance from values + TableSourceNodeOptions(std::shared_ptr table, + int64_t max_batch_size = kDefaultMaxBatchSize) + : table(std::move(table)), max_batch_size(max_batch_size) {} + + /// \brief a table which acts as the data source + std::shared_ptr
table; + /// \brief size of batches to emit from this node + /// If the table is larger the node will emit multiple batches from the + /// the table to be processed in parallel. + int64_t max_batch_size; +}; + +/// \brief define a lazily resolved Arrow table. +/// +/// The table uniquely identified by the names can typically be resolved at the time when +/// the plan is to be consumed. +/// +/// This node is for serialization purposes only and can never be executed. +class ARROW_ACERO_EXPORT NamedTableNodeOptions : public ExecNodeOptions { + public: + /// Create an instance from values + NamedTableNodeOptions(std::vector names, std::shared_ptr schema) + : names(std::move(names)), schema(std::move(schema)) {} + + /// \brief the names to put in the serialized plan + std::vector names; + /// \brief the output schema of the table + std::shared_ptr schema; +}; + +/// \brief a source node which feeds data from a synchronous iterator of batches +/// +/// ItMaker is a maker of an iterator of tabular data. +/// +/// The node can be configured to use an I/O executor. If set then each time the +/// iterator is polled a new I/O thread task will be created to do the polling. This +/// allows a blocking iterator to stay off the CPU thread pool. +template +class ARROW_ACERO_EXPORT SchemaSourceNodeOptions : public ExecNodeOptions { + public: + /// Create an instance that will create a new task on io_executor for each iteration + SchemaSourceNodeOptions(std::shared_ptr schema, ItMaker it_maker, + arrow::internal::Executor* io_executor) + : schema(std::move(schema)), + it_maker(std::move(it_maker)), + io_executor(io_executor), + requires_io(true) {} + + /// Create an instance that will either iterate synchronously or use the default I/O + /// executor + SchemaSourceNodeOptions(std::shared_ptr schema, ItMaker it_maker, + bool requires_io = false) + : schema(std::move(schema)), + it_maker(std::move(it_maker)), + io_executor(NULLPTR), + requires_io(requires_io) {} + + /// \brief The schema of the record batches from the iterator + std::shared_ptr schema; + + /// \brief A maker of an iterator which acts as the data source + ItMaker it_maker; + + /// \brief The executor to use for scanning the iterator + /// + /// Defaults to the default I/O executor. Only used if requires_io is true. + /// If requires_io is false then this MUST be nullptr. + arrow::internal::Executor* io_executor; + + /// \brief If true then items will be fetched from the iterator on a dedicated I/O + /// thread to keep I/O off the CPU thread + bool requires_io; +}; + +/// a source node that reads from a RecordBatchReader +/// +/// Each iteration of the RecordBatchReader will be run on a new thread task created +/// on the I/O thread pool. +class ARROW_ACERO_EXPORT RecordBatchReaderSourceNodeOptions : public ExecNodeOptions { + public: + /// Create an instance from values + RecordBatchReaderSourceNodeOptions(std::shared_ptr reader, + arrow::internal::Executor* io_executor = NULLPTR) + : reader(std::move(reader)), io_executor(io_executor) {} + + /// \brief The RecordBatchReader which acts as the data source + std::shared_ptr reader; + + /// \brief The executor to use for the reader + /// + /// Defaults to the default I/O executor. + arrow::internal::Executor* io_executor; +}; + +/// a source node that reads from an iterator of array vectors +using ArrayVectorIteratorMaker = std::function>()>; +/// \brief An extended Source node which accepts a schema and array-vectors +class ARROW_ACERO_EXPORT ArrayVectorSourceNodeOptions + : public SchemaSourceNodeOptions { + using SchemaSourceNodeOptions::SchemaSourceNodeOptions; +}; + +/// a source node that reads from an iterator of ExecBatch +using ExecBatchIteratorMaker = std::function>()>; +/// \brief An extended Source node which accepts a schema and exec-batches +class ARROW_ACERO_EXPORT ExecBatchSourceNodeOptions + : public SchemaSourceNodeOptions { + public: + using SchemaSourceNodeOptions::SchemaSourceNodeOptions; + ExecBatchSourceNodeOptions(std::shared_ptr schema, + std::vector batches, + ::arrow::internal::Executor* io_executor); + ExecBatchSourceNodeOptions(std::shared_ptr schema, + std::vector batches, bool requires_io = false); +}; + +using RecordBatchIteratorMaker = std::function>()>; +/// a source node that reads from an iterator of RecordBatch +class ARROW_ACERO_EXPORT RecordBatchSourceNodeOptions + : public SchemaSourceNodeOptions { + using SchemaSourceNodeOptions::SchemaSourceNodeOptions; +}; + +/// \brief a node which excludes some rows from batches passed through it +/// +/// filter_expression will be evaluated against each batch which is pushed to +/// this node. Any rows for which filter_expression does not evaluate to `true` will be +/// excluded in the batch emitted by this node. +/// +/// This node will emit empty batches if all rows are excluded. This is done +/// to avoid gaps in the ordering. +class ARROW_ACERO_EXPORT FilterNodeOptions : public ExecNodeOptions { + public: + /// \brief create an instance from values + explicit FilterNodeOptions(Expression filter_expression) + : filter_expression(std::move(filter_expression)) {} + + /// \brief the expression to filter batches + /// + /// The return type of this expression must be boolean + Expression filter_expression; +}; + +/// \brief a node which selects a specified subset from the input +class ARROW_ACERO_EXPORT FetchNodeOptions : public ExecNodeOptions { + public: + static constexpr std::string_view kName = "fetch"; + /// \brief create an instance from values + FetchNodeOptions(int64_t offset, int64_t count) : offset(offset), count(count) {} + /// \brief the number of rows to skip + int64_t offset; + /// \brief the number of rows to keep (not counting skipped rows) + int64_t count; +}; + +/// \brief a node which executes expressions on input batches, producing batches +/// of the same length with new columns. +/// +/// Each expression will be evaluated against each batch which is pushed to +/// this node to produce a corresponding output column. +/// +/// If names are not provided, the string representations of exprs will be used. +class ARROW_ACERO_EXPORT ProjectNodeOptions : public ExecNodeOptions { + public: + /// \brief create an instance from values + explicit ProjectNodeOptions(std::vector expressions, + std::vector names = {}) + : expressions(std::move(expressions)), names(std::move(names)) {} + + /// \brief the expressions to run on the batches + /// + /// The output will have one column for each expression. If you wish to keep any of + /// the columns from the input then you should create a simple field_ref expression + /// for that column. + std::vector expressions; + /// \brief the names of the output columns + /// + /// If this is not specified then the result of calling ToString on the expression will + /// be used instead + /// + /// This list should either be empty or have the same length as `expressions` + std::vector names; +}; + +/// \brief a node which aggregates input batches and calculates summary statistics +/// +/// The node can summarize the entire input or it can group the input with grouping keys +/// and segment keys. +/// +/// By default, the aggregate node is a pipeline breaker. It must accumulate all input +/// before any output is produced. Segment keys are a performance optimization. If +/// you know your input is already partitioned by one or more columns then you can +/// specify these as segment keys. At each change in the segment keys the node will +/// emit values for all data seen so far. +/// +/// Segment keys are currently limited to single-threaded mode. +/// +/// Both keys and segment-keys determine the group. However segment-keys are also used +/// for determining grouping segments, which should be large, and allow streaming a +/// partial aggregation result after processing each segment. One common use-case for +/// segment-keys is ordered aggregation, in which the segment-key attribute specifies a +/// column with non-decreasing values or a lexicographically-ordered set of such columns. +/// +/// If the keys attribute is a non-empty vector, then each aggregate in `aggregates` is +/// expected to be a HashAggregate function. If the keys attribute is an empty vector, +/// then each aggregate is assumed to be a ScalarAggregate function. +/// +/// If the segment_keys attribute is a non-empty vector, then segmented aggregation, as +/// described above, applies. +/// +/// The keys and segment_keys vectors must be disjoint. +/// +/// If no measures are provided then you will simply get the list of unique keys. +/// +/// This node outputs segment keys first, followed by regular keys, followed by one +/// column for each aggregate. +class ARROW_ACERO_EXPORT AggregateNodeOptions : public ExecNodeOptions { + public: + /// \brief create an instance from values + explicit AggregateNodeOptions(std::vector aggregates, + std::vector keys = {}, + std::vector segment_keys = {}) + : aggregates(std::move(aggregates)), + keys(std::move(keys)), + segment_keys(std::move(segment_keys)) {} + + // aggregations which will be applied to the targeted fields + std::vector aggregates; + // keys by which aggregations will be grouped (optional) + std::vector keys; + // keys by which aggregations will be segmented (optional) + std::vector segment_keys; +}; + +/// \brief a default value at which backpressure will be applied +constexpr int32_t kDefaultBackpressureHighBytes = 1 << 30; // 1GiB +/// \brief a default value at which backpressure will be removed +constexpr int32_t kDefaultBackpressureLowBytes = 1 << 28; // 256MiB + +/// \brief an interface that can be queried for backpressure statistics +class ARROW_ACERO_EXPORT BackpressureMonitor { + public: + virtual ~BackpressureMonitor() = default; + /// \brief fetches the number of bytes currently queued up + virtual uint64_t bytes_in_use() = 0; + /// \brief checks to see if backpressure is currently applied + virtual bool is_paused() = 0; +}; + +/// \brief Options to control backpressure behavior +struct ARROW_ACERO_EXPORT BackpressureOptions { + /// \brief Create default options that perform no backpressure + BackpressureOptions() : resume_if_below(0), pause_if_above(0) {} + /// \brief Create options that will perform backpressure + /// + /// \param resume_if_below The producer should resume producing if the backpressure + /// queue has fewer than resume_if_below items. + /// \param pause_if_above The producer should pause producing if the backpressure + /// queue has more than pause_if_above items + BackpressureOptions(uint64_t resume_if_below, uint64_t pause_if_above) + : resume_if_below(resume_if_below), pause_if_above(pause_if_above) {} + + /// \brief create an instance using default values for backpressure limits + static BackpressureOptions DefaultBackpressure() { + return BackpressureOptions(kDefaultBackpressureLowBytes, + kDefaultBackpressureHighBytes); + } + + /// \brief helper method to determine if backpressure is disabled + /// \return true if pause_if_above is greater than zero, false otherwise + bool should_apply_backpressure() const { return pause_if_above > 0; } + + /// \brief the number of bytes at which the producer should resume producing + uint64_t resume_if_below; + /// \brief the number of bytes at which the producer should pause producing + /// + /// If this is <= 0 then backpressure will be disabled + uint64_t pause_if_above; +}; + +/// \brief a sink node which collects results in a queue +/// +/// Emitted batches will only be ordered if there is a meaningful ordering +/// and sequence_output is not set to false. +class ARROW_ACERO_EXPORT SinkNodeOptions : public ExecNodeOptions { + public: + explicit SinkNodeOptions(std::function>()>* generator, + std::shared_ptr* schema, + BackpressureOptions backpressure = {}, + BackpressureMonitor** backpressure_monitor = NULLPTR, + std::optional sequence_output = std::nullopt) + : generator(generator), + schema(schema), + backpressure(backpressure), + backpressure_monitor(backpressure_monitor), + sequence_output(sequence_output) {} + + explicit SinkNodeOptions(std::function>()>* generator, + BackpressureOptions backpressure = {}, + BackpressureMonitor** backpressure_monitor = NULLPTR, + std::optional sequence_output = std::nullopt) + : generator(generator), + schema(NULLPTR), + backpressure(std::move(backpressure)), + backpressure_monitor(backpressure_monitor), + sequence_output(sequence_output) {} + + /// \brief A pointer to a generator of batches. + /// + /// This will be set when the node is added to the plan and should be used to consume + /// data from the plan. If this function is not called frequently enough then the sink + /// node will start to accumulate data and may apply backpressure. + std::function>()>* generator; + /// \brief A pointer which will be set to the schema of the generated batches + /// + /// This is optional, if nullptr is passed in then it will be ignored. + /// This will be set when the node is added to the plan, before StartProducing is called + std::shared_ptr* schema; + /// \brief Options to control when to apply backpressure + /// + /// This is optional, the default is to never apply backpressure. If the plan is not + /// consumed quickly enough the system may eventually run out of memory. + BackpressureOptions backpressure; + /// \brief A pointer to a backpressure monitor + /// + /// This will be set when the node is added to the plan. This can be used to inspect + /// the amount of data currently queued in the sink node. This is an optional utility + /// and backpressure can be applied even if this is not used. + BackpressureMonitor** backpressure_monitor; + /// \brief Controls whether batches should be emitted immediately or sequenced in order + /// + /// \see QueryOptions for more details + std::optional sequence_output; +}; + +/// \brief Control used by a SinkNodeConsumer to pause & resume +/// +/// Callers should ensure that they do not call Pause and Resume simultaneously and they +/// should sequence things so that a call to Pause() is always followed by an eventual +/// call to Resume() +class ARROW_ACERO_EXPORT BackpressureControl { + public: + virtual ~BackpressureControl() = default; + /// \brief Ask the input to pause + /// + /// This is best effort, batches may continue to arrive + /// Must eventually be followed by a call to Resume() or deadlock will occur + virtual void Pause() = 0; + /// \brief Ask the input to resume + virtual void Resume() = 0; +}; + +/// \brief a sink node that consumes the data as part of the plan using callbacks +class ARROW_ACERO_EXPORT SinkNodeConsumer { + public: + virtual ~SinkNodeConsumer() = default; + /// \brief Prepare any consumer state + /// + /// This will be run once the schema is finalized as the plan is starting and + /// before any calls to Consume. A common use is to save off the schema so that + /// batches can be interpreted. + virtual Status Init(const std::shared_ptr& schema, + BackpressureControl* backpressure_control, ExecPlan* plan) = 0; + /// \brief Consume a batch of data + virtual Status Consume(ExecBatch batch) = 0; + /// \brief Signal to the consumer that the last batch has been delivered + /// + /// The returned future should only finish when all outstanding tasks have completed + /// + /// If the plan is ended early or aborts due to an error then this will not be + /// called. + virtual Future<> Finish() = 0; +}; + +/// \brief Add a sink node which consumes data within the exec plan run +class ARROW_ACERO_EXPORT ConsumingSinkNodeOptions : public ExecNodeOptions { + public: + explicit ConsumingSinkNodeOptions(std::shared_ptr consumer, + std::vector names = {}, + std::optional sequence_output = std::nullopt) + : consumer(std::move(consumer)), + names(std::move(names)), + sequence_output(sequence_output) {} + + std::shared_ptr consumer; + /// \brief Names to rename the sink's schema fields to + /// + /// If specified then names must be provided for all fields. Currently, only a flat + /// schema is supported (see GH-31875). + /// + /// If not specified then names will be generated based on the source data. + std::vector names; + /// \brief Controls whether batches should be emitted immediately or sequenced in order + /// + /// \see QueryOptions for more details + std::optional sequence_output; +}; + +/// \brief Make a node which sorts rows passed through it +/// +/// All batches pushed to this node will be accumulated, then sorted, by the given +/// fields. Then sorted batches will be forwarded to the generator in sorted order. +class ARROW_ACERO_EXPORT OrderBySinkNodeOptions : public SinkNodeOptions { + public: + /// \brief create an instance from values + explicit OrderBySinkNodeOptions( + SortOptions sort_options, + std::function>()>* generator) + : SinkNodeOptions(generator), sort_options(std::move(sort_options)) {} + + /// \brief options describing which columns and direction to sort + SortOptions sort_options; +}; + +/// \brief Apply a new ordering to data +/// +/// Currently this node works by accumulating all data, sorting, and then emitting +/// the new data with an updated batch index. +/// +/// Larger-than-memory sort is not currently supported. +class ARROW_ACERO_EXPORT OrderByNodeOptions : public ExecNodeOptions { + public: + static constexpr std::string_view kName = "order_by"; + explicit OrderByNodeOptions(Ordering ordering) : ordering(std::move(ordering)) {} + + /// \brief The new ordering to apply to outgoing data + Ordering ordering; +}; + +enum class JoinType { + LEFT_SEMI, + RIGHT_SEMI, + LEFT_ANTI, + RIGHT_ANTI, + INNER, + LEFT_OUTER, + RIGHT_OUTER, + FULL_OUTER +}; + +std::string ToString(JoinType t); + +enum class JoinKeyCmp { EQ, IS }; + +/// \brief a node which implements a join operation using a hash table +class ARROW_ACERO_EXPORT HashJoinNodeOptions : public ExecNodeOptions { + public: + static constexpr const char* default_output_suffix_for_left = ""; + static constexpr const char* default_output_suffix_for_right = ""; + /// \brief create an instance from values that outputs all columns + HashJoinNodeOptions( + JoinType in_join_type, std::vector in_left_keys, + std::vector in_right_keys, Expression filter = literal(true), + std::string output_suffix_for_left = default_output_suffix_for_left, + std::string output_suffix_for_right = default_output_suffix_for_right, + bool disable_bloom_filter = false) + : join_type(in_join_type), + left_keys(std::move(in_left_keys)), + right_keys(std::move(in_right_keys)), + output_all(true), + output_suffix_for_left(std::move(output_suffix_for_left)), + output_suffix_for_right(std::move(output_suffix_for_right)), + filter(std::move(filter)), + disable_bloom_filter(disable_bloom_filter) { + this->key_cmp.resize(this->left_keys.size()); + for (size_t i = 0; i < this->left_keys.size(); ++i) { + this->key_cmp[i] = JoinKeyCmp::EQ; + } + } + /// \brief create an instance from keys + /// + /// This will create an inner join that outputs all columns and has no post join filter + /// + /// `in_left_keys` should have the same length and types as `in_right_keys` + /// @param in_left_keys the keys in the left input + /// @param in_right_keys the keys in the right input + HashJoinNodeOptions(std::vector in_left_keys, + std::vector in_right_keys) + : left_keys(std::move(in_left_keys)), right_keys(std::move(in_right_keys)) { + this->join_type = JoinType::INNER; + this->output_all = true; + this->output_suffix_for_left = default_output_suffix_for_left; + this->output_suffix_for_right = default_output_suffix_for_right; + this->key_cmp.resize(this->left_keys.size()); + for (size_t i = 0; i < this->left_keys.size(); ++i) { + this->key_cmp[i] = JoinKeyCmp::EQ; + } + this->filter = literal(true); + } + /// \brief create an instance from values using JoinKeyCmp::EQ for all comparisons + HashJoinNodeOptions( + JoinType join_type, std::vector left_keys, + std::vector right_keys, std::vector left_output, + std::vector right_output, Expression filter = literal(true), + std::string output_suffix_for_left = default_output_suffix_for_left, + std::string output_suffix_for_right = default_output_suffix_for_right, + bool disable_bloom_filter = false) + : join_type(join_type), + left_keys(std::move(left_keys)), + right_keys(std::move(right_keys)), + output_all(false), + left_output(std::move(left_output)), + right_output(std::move(right_output)), + output_suffix_for_left(std::move(output_suffix_for_left)), + output_suffix_for_right(std::move(output_suffix_for_right)), + filter(std::move(filter)), + disable_bloom_filter(disable_bloom_filter) { + this->key_cmp.resize(this->left_keys.size()); + for (size_t i = 0; i < this->left_keys.size(); ++i) { + this->key_cmp[i] = JoinKeyCmp::EQ; + } + } + /// \brief create an instance from values + HashJoinNodeOptions( + JoinType join_type, std::vector left_keys, + std::vector right_keys, std::vector left_output, + std::vector right_output, std::vector key_cmp, + Expression filter = literal(true), + std::string output_suffix_for_left = default_output_suffix_for_left, + std::string output_suffix_for_right = default_output_suffix_for_right, + bool disable_bloom_filter = false) + : join_type(join_type), + left_keys(std::move(left_keys)), + right_keys(std::move(right_keys)), + output_all(false), + left_output(std::move(left_output)), + right_output(std::move(right_output)), + key_cmp(std::move(key_cmp)), + output_suffix_for_left(std::move(output_suffix_for_left)), + output_suffix_for_right(std::move(output_suffix_for_right)), + filter(std::move(filter)), + disable_bloom_filter(disable_bloom_filter) {} + + HashJoinNodeOptions() = default; + + // type of join (inner, left, semi...) + JoinType join_type = JoinType::INNER; + // key fields from left input + std::vector left_keys; + // key fields from right input + std::vector right_keys; + // if set all valid fields from both left and right input will be output + // (and field ref vectors for output fields will be ignored) + bool output_all = false; + // output fields passed from left input + std::vector left_output; + // output fields passed from right input + std::vector right_output; + // key comparison function (determines whether a null key is equal another null + // key or not) + std::vector key_cmp; + // suffix added to names of output fields coming from left input (used to distinguish, + // if necessary, between fields of the same name in left and right input and can be left + // empty if there are no name collisions) + std::string output_suffix_for_left; + // suffix added to names of output fields coming from right input + std::string output_suffix_for_right; + // residual filter which is applied to matching rows. Rows that do not match + // the filter are not included. The filter is applied against the + // concatenated input schema (left fields then right fields) and can reference + // fields that are not included in the output. + Expression filter = literal(true); + // whether or not to disable Bloom filters in this join + bool disable_bloom_filter = false; +}; + +/// \brief a node which implements the asof join operation +/// +/// Note, this API is experimental and will change in the future +/// +/// This node takes one left table and any number of right tables, and asof joins them +/// together. Batches produced by each input must be ordered by the "on" key. +/// This node will output one row for each row in the left table. +class ARROW_ACERO_EXPORT AsofJoinNodeOptions : public ExecNodeOptions { + public: + /// \brief Keys for one input table of the AsofJoin operation + /// + /// The keys must be consistent across the input tables: + /// Each "on" key must refer to a field of the same type and units across the tables. + /// Each "by" key must refer to a list of fields of the same types across the tables. + struct Keys { + /// \brief "on" key for the join. + /// + /// The input table must be sorted by the "on" key. Must be a single field of a common + /// type. An inexact match is used on the "on" key, i.e. a row is considered a + /// match if and only if `right.on - left.on` is in the range + /// `[min(0, tolerance), max(0, tolerance)]`. + /// Currently, the "on" key must be of an integer, date, or timestamp type. + FieldRef on_key; + /// \brief "by" key for the join. + /// + /// Each input table must have each field of the "by" key. Exact equality is used for + /// each field of the "by" key. + /// Currently, each field of the "by" key must be of an integer, date, timestamp, or + /// base-binary type. + std::vector by_key; + }; + + AsofJoinNodeOptions(std::vector input_keys, int64_t tolerance) + : input_keys(std::move(input_keys)), tolerance(tolerance) {} + + /// \brief AsofJoin keys per input table. At least two keys must be given. The first key + /// corresponds to a left table and all other keys correspond to right tables for the + /// as-of-join. + /// + /// \see `Keys` for details. + std::vector input_keys; + /// \brief Tolerance for inexact "on" key matching. A right row is considered a match + /// with a left row if `right.on - left.on` is in the range + /// `[min(0, tolerance), max(0, tolerance)]`. `tolerance` may be: + /// - negative, in which case a past-as-of-join occurs (match iff + /// `tolerance <= right.on - left.on <= 0`); + /// - or positive, in which case a future-as-of-join occurs (match iff + /// `0 <= right.on - left.on <= tolerance`); + /// - or zero, in which case an exact-as-of-join occurs (match iff + /// `right.on == left.on`). + /// + /// The tolerance is interpreted in the same units as the "on" key. + int64_t tolerance; +}; + +/// \brief a node which select top_k/bottom_k rows passed through it +/// +/// All batches pushed to this node will be accumulated, then selected, by the given +/// fields. Then sorted batches will be forwarded to the generator in sorted order. +class ARROW_ACERO_EXPORT SelectKSinkNodeOptions : public SinkNodeOptions { + public: + explicit SelectKSinkNodeOptions( + SelectKOptions select_k_options, + std::function>()>* generator) + : SinkNodeOptions(generator), select_k_options(std::move(select_k_options)) {} + + /// SelectK options + SelectKOptions select_k_options; +}; + +/// \brief a sink node which accumulates all output into a table +class ARROW_ACERO_EXPORT TableSinkNodeOptions : public ExecNodeOptions { + public: + /// \brief create an instance from values + explicit TableSinkNodeOptions(std::shared_ptr
* output_table, + std::optional sequence_output = std::nullopt) + : output_table(output_table), sequence_output(sequence_output) {} + + /// \brief an "out parameter" specifying the table that will be created + /// + /// Must not be null and remain valid for the entirety of the plan execution. After the + /// plan has completed this will be set to point to the result table + std::shared_ptr
* output_table; + /// \brief Controls whether batches should be emitted immediately or sequenced in order + /// + /// \see QueryOptions for more details + std::optional sequence_output; + /// \brief Custom names to use for the columns. + /// + /// If specified then names must be provided for all fields. Currently, only a flat + /// schema is supported (see GH-31875). + /// + /// If not specified then names will be generated based on the source data. + std::vector names; +}; + +/// \brief a row template that describes one row that will be generated for each input row +struct ARROW_ACERO_EXPORT PivotLongerRowTemplate { + PivotLongerRowTemplate(std::vector feature_values, + std::vector> measurement_values) + : feature_values(std::move(feature_values)), + measurement_values(std::move(measurement_values)) {} + /// A (typically unique) set of feature values for the template, usually derived from a + /// column name + /// + /// These will be used to populate the feature columns + std::vector feature_values; + /// The fields containing the measurements to use for this row + /// + /// These will be used to populate the measurement columns. If nullopt then nulls + /// will be inserted for the given value. + std::vector> measurement_values; +}; + +/// \brief Reshape a table by turning some columns into additional rows +/// +/// This operation is sometimes also referred to as UNPIVOT +/// +/// This is typically done when there are multiple observations in each row in order to +/// transform to a table containing a single observation per row. +/// +/// For example: +/// +/// | time | left_temp | right_temp | +/// | ---- | --------- | ---------- | +/// | 1 | 10 | 20 | +/// | 2 | 15 | 18 | +/// +/// The above table contains two observations per row. There is an implicit feature +/// "location" (left vs right) and a measurement "temp". What we really want is: +/// +/// | time | location | temp | +/// | --- | --- | --- | +/// | 1 | left | 10 | +/// | 1 | right | 20 | +/// | 2 | left | 15 | +/// | 2 | right | 18 | +/// +/// For a more complex example consider: +/// +/// | time | ax1 | ay1 | bx1 | ay2 | +/// | ---- | --- | --- | --- | --- | +/// | 0 | 1 | 2 | 3 | 4 | +/// +/// We can pretend a vs b and x vs y are features while 1 and 2 are two different +/// kinds of measurements. We thus want to pivot to +/// +/// | time | a/b | x/y | f1 | f2 | +/// | ---- | --- | --- | ---- | ---- | +/// | 0 | a | x | 1 | null | +/// | 0 | a | y | 2 | 4 | +/// | 0 | b | x | 3 | null | +/// +/// To do this we create a row template for each combination of features. One should +/// be able to do this purely by looking at the column names. For example, given the +/// above columns "ax1", "ay1", "bx1", and "ay2" we know we have three feature +/// combinations (a, x), (a, y), and (b, x). Similarly, we know we have two possible +/// measurements, "1" and "2". +/// +/// For each combination of features we create a row template. In each row template we +/// describe the combination and then list which columns to use for the measurements. +/// If a measurement doesn't exist for a given combination then we use nullopt. +/// +/// So, for our above example, we have: +/// +/// (a, x): names={"a", "x"}, values={"ax1", nullopt} +/// (a, y): names={"a", "y"}, values={"ay1", "ay2"} +/// (b, x): names={"b", "x"}, values={"bx1", nullopt} +/// +/// Finishing it off we name our new columns: +/// feature_field_names={"a/b","x/y"} +/// measurement_field_names={"f1", "f2"} +class ARROW_ACERO_EXPORT PivotLongerNodeOptions : public ExecNodeOptions { + public: + static constexpr std::string_view kName = "pivot_longer"; + /// One or more row templates to create new output rows + /// + /// Normally there are at least two row templates. The output # of rows + /// will be the input # of rows * the number of row templates + std::vector row_templates; + /// The names of the columns which describe the new features + std::vector feature_field_names; + /// The names of the columns which represent the measurements + std::vector measurement_field_names; +}; + +/// @} + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/order_by_impl.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/order_by_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..9b5a0f69a69ffc8f23fb5416e82777d2d06f0a00 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/order_by_impl.h @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/acero/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" + +namespace arrow { + +using compute::ExecContext; + +namespace acero { + +class OrderByImpl { + public: + virtual ~OrderByImpl() = default; + + virtual void InputReceived(const std::shared_ptr& batch) = 0; + + virtual Result DoFinish() = 0; + + virtual std::string ToString() const = 0; + + static Result> MakeSort( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options); + + static Result> MakeSelectK( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options); +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/partition_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/partition_util.h new file mode 100644 index 0000000000000000000000000000000000000000..52cc47bb8a99f5fcc32defa09698c715025f322b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/partition_util.h @@ -0,0 +1,186 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/acero/util.h" +#include "arrow/buffer.h" +#include "arrow/util/pcg_random.h" + +namespace arrow { +namespace acero { + +class PartitionSort { + public: + /// \brief Bucket sort rows on partition ids in O(num_rows) time. + /// + /// Include in the output exclusive cumulative sum of bucket sizes. + /// This corresponds to ranges in the sorted array containing all row ids for + /// each of the partitions. + /// + /// prtn_ranges must be initialized and have at least num_prtns + 1 elements + /// when this method returns prtn_ranges[i] will contains the total number of + /// elements in partitions 0 through i. prtn_ranges[0] will be 0. + /// + /// prtn_id_impl must be a function that takes in a row id (int) and returns + /// a partition id (int). The returned partition id must be between 0 and + /// num_prtns (exclusive). + /// + /// output_pos_impl is a function that takes in a row id (int) and a position (int) + /// in the bucket sorted output. The function should insert the row in the + /// output. + /// + /// For example: + /// + /// in_arr: [5, 7, 2, 3, 5, 4] + /// num_prtns: 3 + /// prtn_id_impl: [&in_arr] (int row_id) { return in_arr[row_id] / 3; } + /// output_pos_impl: [&sorted_row_ids] (int row_id, int pos) { sorted_row_ids[pos] = + /// row_id; } + /// + /// After Execution + /// sorted_row_ids: [2, 0, 3, 4, 5, 1] + /// prtn_ranges: [0, 1, 5, 6] + template + static void Eval(int64_t num_rows, int num_prtns, uint16_t* prtn_ranges, + INPUT_PRTN_ID_FN prtn_id_impl, OUTPUT_POS_FN output_pos_impl) { + ARROW_DCHECK(num_rows > 0 && num_rows <= (1 << 15)); + ARROW_DCHECK(num_prtns >= 1 && num_prtns <= (1 << 15)); + + memset(prtn_ranges, 0, (num_prtns + 1) * sizeof(uint16_t)); + + for (int64_t i = 0; i < num_rows; ++i) { + int prtn_id = static_cast(prtn_id_impl(i)); + ++prtn_ranges[prtn_id + 1]; + } + + uint16_t sum = 0; + for (int i = 0; i < num_prtns; ++i) { + uint16_t sum_next = sum + prtn_ranges[i + 1]; + prtn_ranges[i + 1] = sum; + sum = sum_next; + } + + for (int64_t i = 0; i < num_rows; ++i) { + int prtn_id = static_cast(prtn_id_impl(i)); + int pos = prtn_ranges[prtn_id + 1]++; + output_pos_impl(i, pos); + } + } +}; + +/// \brief A control for synchronizing threads on a partitionable workload +class PartitionLocks { + public: + PartitionLocks(); + ~PartitionLocks(); + /// \brief Initializes the control, must be called before use + /// + /// \param num_threads Maximum number of threads that will access the partitions + /// \param num_prtns Number of partitions to synchronize + void Init(size_t num_threads, int num_prtns); + /// \brief Cleans up the control, it should not be used after this call + void CleanUp(); + /// \brief Acquire a partition to work on one + /// + /// \param thread_id The index of the thread trying to acquire the partition lock + /// \param num_prtns Length of prtns_to_try, must be <= num_prtns used in Init + /// \param prtns_to_try An array of partitions that still have remaining work + /// \param limit_retries If false, this method will spinwait forever until success + /// \param max_retries Max times to attempt checking out work before returning false + /// \param[out] locked_prtn_id The id of the partition locked + /// \param[out] locked_prtn_id_pos The index of the partition locked in prtns_to_try + /// \return True if a partition was locked, false if max_retries was attempted + /// without successfully acquiring a lock + /// + /// This method is thread safe + bool AcquirePartitionLock(size_t thread_id, int num_prtns, const int* prtns_to_try, + bool limit_retries, int max_retries, int* locked_prtn_id, + int* locked_prtn_id_pos); + /// \brief Release a partition so that other threads can work on it + void ReleasePartitionLock(int prtn_id); + + // Executes (synchronously and using current thread) the same operation on a set of + // multiple partitions. Tries to minimize partition locking overhead by randomizing and + // adjusting order in which partitions are processed. + // + // PROCESS_PRTN_FN is a callback which will be executed for each partition after + // acquiring the lock for that partition. It gets partition id as an argument. + // IS_PRTN_EMPTY_FN is a callback which filters out (when returning true) partitions + // with specific ids from processing. + // + template + Status ForEachPartition(size_t thread_id, + /*scratch space buffer with space for one element per partition; + dirty in and dirty out*/ + int* temp_unprocessed_prtns, IS_PRTN_EMPTY_FN is_prtn_empty_fn, + PROCESS_PRTN_FN process_prtn_fn) { + int num_unprocessed_partitions = 0; + for (int i = 0; i < num_prtns_; ++i) { + bool is_prtn_empty = is_prtn_empty_fn(i); + if (!is_prtn_empty) { + temp_unprocessed_prtns[num_unprocessed_partitions++] = i; + } + } + while (num_unprocessed_partitions > 0) { + int locked_prtn_id; + int locked_prtn_id_pos; + AcquirePartitionLock(thread_id, num_unprocessed_partitions, temp_unprocessed_prtns, + /*limit_retries=*/false, /*max_retries=*/-1, &locked_prtn_id, + &locked_prtn_id_pos); + { + class AutoReleaseLock { + public: + AutoReleaseLock(PartitionLocks* locks, int prtn_id) + : locks(locks), prtn_id(prtn_id) {} + ~AutoReleaseLock() { locks->ReleasePartitionLock(prtn_id); } + PartitionLocks* locks; + int prtn_id; + } auto_release_lock(this, locked_prtn_id); + ARROW_RETURN_NOT_OK(process_prtn_fn(locked_prtn_id)); + } + if (locked_prtn_id_pos < num_unprocessed_partitions - 1) { + temp_unprocessed_prtns[locked_prtn_id_pos] = + temp_unprocessed_prtns[num_unprocessed_partitions - 1]; + } + --num_unprocessed_partitions; + } + return Status::OK(); + } + + private: + std::atomic* lock_ptr(int prtn_id); + int random_int(size_t thread_id, int num_values); + + struct PartitionLock { + static constexpr int kCacheLineBytes = 64; + std::atomic lock; + uint8_t padding[kCacheLineBytes]; + }; + int num_prtns_; + std::unique_ptr locks_; + std::unique_ptr rngs_; +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/query_context.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/query_context.h new file mode 100644 index 0000000000000000000000000000000000000000..3eff299439828e602558e5ebc278660bb7ce37eb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/query_context.h @@ -0,0 +1,151 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +#pragma once + +#include + +#include "arrow/acero/exec_plan.h" +#include "arrow/acero/task_util.h" +#include "arrow/acero/util.h" +#include "arrow/compute/exec.h" +#include "arrow/io/interfaces.h" +#include "arrow/util/async_util.h" +#include "arrow/util/type_fwd.h" + +namespace arrow { + +using compute::default_exec_context; +using io::IOContext; + +namespace acero { + +class ARROW_ACERO_EXPORT QueryContext { + public: + QueryContext(QueryOptions opts = {}, + ExecContext exec_context = *default_exec_context()); + + Status Init(arrow::util::AsyncTaskScheduler* scheduler); + + const ::arrow::internal::CpuInfo* cpu_info() const; + int64_t hardware_flags() const; + const QueryOptions& options() const { return options_; } + MemoryPool* memory_pool() const { return exec_context_.memory_pool(); } + ::arrow::internal::Executor* executor() const { return exec_context_.executor(); } + ExecContext* exec_context() { return &exec_context_; } + IOContext* io_context() { return &io_context_; } + TaskScheduler* scheduler() { return task_scheduler_.get(); } + arrow::util::AsyncTaskScheduler* async_scheduler() { return async_scheduler_; } + + size_t GetThreadIndex(); + size_t max_concurrency() const; + + /// \brief Start an external task + /// + /// This should be avoided if possible. It is kept in for now for legacy + /// purposes. This should be called before the external task is started. If + /// a valid future is returned then it should be marked complete when the + /// external task has finished. + /// + /// \param name A name to give the task for traceability and debugging + /// + /// \return an invalid future if the plan has already ended, otherwise this + /// returns a future that must be completed when the external task + /// finishes. + Result> BeginExternalTask(std::string_view name); + + /// \brief Add a single function as a task to the query's task group + /// on the compute threadpool. + /// + /// \param fn The task to run. Takes no arguments and returns a Status. + /// \param name A name to give the task for traceability and debugging + void ScheduleTask(std::function fn, std::string_view name); + /// \brief Add a single function as a task to the query's task group + /// on the compute threadpool. + /// + /// \param fn The task to run. Takes the thread index and returns a Status. + /// \param name A name to give the task for traceability and debugging + void ScheduleTask(std::function fn, std::string_view name); + /// \brief Add a single function as a task to the query's task group on + /// the IO thread pool + /// + /// \param fn The task to run. Returns a status. + /// \param name A name to give the task for traceability and debugging + void ScheduleIOTask(std::function fn, std::string_view name); + + // Register/Start TaskGroup is a way of performing a "Parallel For" pattern: + // - The task function takes the thread index and the index of the task + // - The on_finished function takes the thread index + // Returns an integer ID that will be used to reference the task group in + // StartTaskGroup. At runtime, call StartTaskGroup with the ID and the number of times + // you'd like the task to be executed. The need to register a task group before use will + // be removed after we rewrite the scheduler. + /// \brief Register a "parallel for" task group with the scheduler + /// + /// \param task The function implementing the task. Takes the thread_index and + /// the task index. + /// \param on_finished The function that gets run once all tasks have been completed. + /// Takes the thread_index. + /// + /// Must be called inside of ExecNode::Init. + int RegisterTaskGroup(std::function task, + std::function on_finished); + + /// \brief Start the task group with the specified ID. This can only + /// be called once per task_group_id. + /// + /// \param task_group_id The ID of the task group to run + /// \param num_tasks The number of times to run the task + Status StartTaskGroup(int task_group_id, int64_t num_tasks); + + // This is an RAII class for keeping track of in-flight file IO. Useful for getting + // an estimate of memory use, and how much memory we expect to be freed soon. + // Returned by ReportTempFileIO. + struct [[nodiscard]] TempFileIOMark { + QueryContext* ctx_; + size_t bytes_; + + TempFileIOMark(QueryContext* ctx, size_t bytes) : ctx_(ctx), bytes_(bytes) { + ctx_->in_flight_bytes_to_disk_.fetch_add(bytes_, std::memory_order_acquire); + } + + ARROW_DISALLOW_COPY_AND_ASSIGN(TempFileIOMark); + + ~TempFileIOMark() { + ctx_->in_flight_bytes_to_disk_.fetch_sub(bytes_, std::memory_order_release); + } + }; + + TempFileIOMark ReportTempFileIO(size_t bytes) { return {this, bytes}; } + + size_t GetCurrentTempFileIO() { return in_flight_bytes_to_disk_.load(); } + + private: + QueryOptions options_; + // To be replaced with Acero-specific context once scheduler is done and + // we don't need ExecContext for kernels + ExecContext exec_context_; + IOContext io_context_; + + arrow::util::AsyncTaskScheduler* async_scheduler_ = NULLPTR; + std::unique_ptr task_scheduler_ = TaskScheduler::Make(); + + ThreadIndexer thread_indexer_; + + std::atomic in_flight_bytes_to_disk_{0}; +}; +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/schema_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/schema_util.h new file mode 100644 index 0000000000000000000000000000000000000000..db3076a58841a6cb85fcc3d5033ef3b74ed18898 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/schema_util.h @@ -0,0 +1,226 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/type.h" // for DataType, FieldRef, Field and Schema + +namespace arrow { + +using internal::checked_cast; + +namespace acero { + +// Identifiers for all different row schemas that are used in a join +// +enum class HashJoinProjection : int { + INPUT = 0, + KEY = 1, + PAYLOAD = 2, + FILTER = 3, + OUTPUT = 4 +}; + +struct SchemaProjectionMap { + static constexpr int kMissingField = -1; + int num_cols; + const int* source_to_base; + const int* base_to_target; + inline int get(int i) const { + assert(i >= 0 && i < num_cols); + assert(source_to_base[i] != kMissingField); + return base_to_target[source_to_base[i]]; + } +}; + +/// Helper class for managing different projections of the same row schema. +/// Used to efficiently map any field in one projection to a corresponding field in +/// another projection. +/// Materialized mappings are generated lazily at the time of the first access. +/// Thread-safe apart from initialization. +template +class SchemaProjectionMaps { + public: + static constexpr int kMissingField = -1; + + Status Init(ProjectionIdEnum full_schema_handle, const Schema& schema, + const std::vector& projection_handles, + const std::vector*>& projections) { + assert(projection_handles.size() == projections.size()); + ARROW_RETURN_NOT_OK(RegisterSchema(full_schema_handle, schema)); + for (size_t i = 0; i < projections.size(); ++i) { + ARROW_RETURN_NOT_OK( + RegisterProjectedSchema(projection_handles[i], *(projections[i]), schema)); + } + RegisterEnd(); + return Status::OK(); + } + + int num_cols(ProjectionIdEnum schema_handle) const { + int id = schema_id(schema_handle); + return static_cast(schemas_[id].second.data_types.size()); + } + + bool is_empty(ProjectionIdEnum schema_handle) const { + return num_cols(schema_handle) == 0; + } + + const std::string& field_name(ProjectionIdEnum schema_handle, int field_id) const { + int id = schema_id(schema_handle); + return schemas_[id].second.field_names[field_id]; + } + + const std::shared_ptr& data_type(ProjectionIdEnum schema_handle, + int field_id) const { + int id = schema_id(schema_handle); + return schemas_[id].second.data_types[field_id]; + } + + const std::vector>& data_types( + ProjectionIdEnum schema_handle) const { + int id = schema_id(schema_handle); + return schemas_[id].second.data_types; + } + + SchemaProjectionMap map(ProjectionIdEnum from, ProjectionIdEnum to) const { + int id_from = schema_id(from); + int id_to = schema_id(to); + SchemaProjectionMap result; + result.num_cols = num_cols(from); + result.source_to_base = mappings_[id_from].data(); + result.base_to_target = inverse_mappings_[id_to].data(); + return result; + } + + protected: + struct FieldInfos { + std::vector field_paths; + std::vector field_names; + std::vector> data_types; + }; + + Status RegisterSchema(ProjectionIdEnum handle, const Schema& schema) { + FieldInfos out_fields; + const FieldVector& in_fields = schema.fields(); + out_fields.field_paths.resize(in_fields.size()); + out_fields.field_names.resize(in_fields.size()); + out_fields.data_types.resize(in_fields.size()); + for (size_t i = 0; i < in_fields.size(); ++i) { + const std::string& name = in_fields[i]->name(); + const std::shared_ptr& type = in_fields[i]->type(); + out_fields.field_paths[i] = static_cast(i); + out_fields.field_names[i] = name; + out_fields.data_types[i] = type; + } + schemas_.push_back(std::make_pair(handle, out_fields)); + return Status::OK(); + } + + Status RegisterProjectedSchema(ProjectionIdEnum handle, + const std::vector& selected_fields, + const Schema& full_schema) { + FieldInfos out_fields; + const FieldVector& in_fields = full_schema.fields(); + out_fields.field_paths.resize(selected_fields.size()); + out_fields.field_names.resize(selected_fields.size()); + out_fields.data_types.resize(selected_fields.size()); + for (size_t i = 0; i < selected_fields.size(); ++i) { + // All fields must be found in schema without ambiguity + ARROW_ASSIGN_OR_RAISE(auto match, selected_fields[i].FindOne(full_schema)); + const std::string& name = in_fields[match[0]]->name(); + const std::shared_ptr& type = in_fields[match[0]]->type(); + out_fields.field_paths[i] = match[0]; + out_fields.field_names[i] = name; + out_fields.data_types[i] = type; + } + schemas_.push_back(std::make_pair(handle, out_fields)); + return Status::OK(); + } + + void RegisterEnd() { + size_t size = schemas_.size(); + mappings_.resize(size); + inverse_mappings_.resize(size); + int id_base = 0; + for (size_t i = 0; i < size; ++i) { + GenerateMapForProjection(static_cast(i), id_base); + } + } + + int schema_id(ProjectionIdEnum schema_handle) const { + for (size_t i = 0; i < schemas_.size(); ++i) { + if (schemas_[i].first == schema_handle) { + return static_cast(i); + } + } + // We should never get here + assert(false); + return -1; + } + + void GenerateMapForProjection(int id_proj, int id_base) { + int num_cols_proj = static_cast(schemas_[id_proj].second.data_types.size()); + int num_cols_base = static_cast(schemas_[id_base].second.data_types.size()); + + std::vector& mapping = mappings_[id_proj]; + std::vector& inverse_mapping = inverse_mappings_[id_proj]; + mapping.resize(num_cols_proj); + inverse_mapping.resize(num_cols_base); + + if (id_proj == id_base) { + for (int i = 0; i < num_cols_base; ++i) { + mapping[i] = inverse_mapping[i] = i; + } + } else { + const FieldInfos& fields_proj = schemas_[id_proj].second; + const FieldInfos& fields_base = schemas_[id_base].second; + for (int i = 0; i < num_cols_base; ++i) { + inverse_mapping[i] = SchemaProjectionMap::kMissingField; + } + for (int i = 0; i < num_cols_proj; ++i) { + int field_id = SchemaProjectionMap::kMissingField; + for (int j = 0; j < num_cols_base; ++j) { + if (fields_proj.field_paths[i] == fields_base.field_paths[j]) { + field_id = j; + // If there are multiple matches for the same input field, + // it will be mapped to the first match. + break; + } + } + assert(field_id != SchemaProjectionMap::kMissingField); + mapping[i] = field_id; + inverse_mapping[field_id] = i; + } + } + } + + // vector used as a mapping from ProjectionIdEnum to fields + std::vector> schemas_; + std::vector> mappings_; + std::vector> inverse_mappings_; +}; + +using HashJoinProjectionMaps = SchemaProjectionMaps; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/task_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/task_util.h new file mode 100644 index 0000000000000000000000000000000000000000..fbd4af699d12795bd92bd385f23a036d63adde38 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/task_util.h @@ -0,0 +1,102 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/acero/visibility.h" +#include "arrow/status.h" +#include "arrow/util/config.h" +#include "arrow/util/logging.h" + +namespace arrow { +namespace acero { + +// Atomic value surrounded by padding bytes to avoid cache line invalidation +// whenever it is modified by a concurrent thread on a different CPU core. +// +template +class AtomicWithPadding { + private: + static constexpr int kCacheLineSize = 64; + uint8_t padding_before[kCacheLineSize]; + + public: + std::atomic value; + + private: + uint8_t padding_after[kCacheLineSize]; +}; + +// Used for asynchronous execution of operations that can be broken into +// a fixed number of symmetric tasks that can be executed concurrently. +// +// Implements priorities between multiple such operations, called task groups. +// +// Allows to specify the maximum number of in-flight tasks at any moment. +// +// Also allows for executing next pending tasks immediately using a caller thread. +// +class ARROW_ACERO_EXPORT TaskScheduler { + public: + using TaskImpl = std::function; + using TaskGroupContinuationImpl = std::function; + using ScheduleImpl = std::function; + using AbortContinuationImpl = std::function; + + virtual ~TaskScheduler() = default; + + // Order in which task groups are registered represents priorities of their tasks + // (the first group has the highest priority). + // + // Returns task group identifier that is used to request operations on the task group. + virtual int RegisterTaskGroup(TaskImpl task_impl, + TaskGroupContinuationImpl cont_impl) = 0; + + virtual void RegisterEnd() = 0; + + // total_num_tasks may be zero, in which case task group continuation will be executed + // immediately + virtual Status StartTaskGroup(size_t thread_id, int group_id, + int64_t total_num_tasks) = 0; + + // Execute given number of tasks immediately using caller thread + virtual Status ExecuteMore(size_t thread_id, int num_tasks_to_execute, + bool execute_all) = 0; + + // Begin scheduling tasks using provided callback and + // the limit on the number of in-flight tasks at any moment. + // + // Scheduling will continue as long as there are waiting tasks. + // + // It will automatically resume whenever new task group gets started. + virtual Status StartScheduling(size_t thread_id, ScheduleImpl schedule_impl, + int num_concurrent_tasks, bool use_sync_execution) = 0; + + // Abort scheduling and execution. + // Used in case of being notified about unrecoverable error for the entire query. + virtual void Abort(AbortContinuationImpl impl) = 0; + + static std::unique_ptr Make(); +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/test_nodes.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/test_nodes.h new file mode 100644 index 0000000000000000000000000000000000000000..7e31aa31b34d7b423ab85ff2e77c1cec0087fa5b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/test_nodes.h @@ -0,0 +1,86 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/acero/options.h" +#include "arrow/acero/test_util_internal.h" +#include "arrow/testing/random.h" + +namespace arrow { +namespace acero { + +// \brief Make a delaying source that is optionally noisy (prints when it emits) +AsyncGenerator> MakeDelayedGen( + Iterator> src, std::string label, double delay_sec, + bool noisy = false); + +// \brief Make a delaying source that is optionally noisy (prints when it emits) +AsyncGenerator> MakeDelayedGen( + AsyncGenerator> src, std::string label, double delay_sec, + bool noisy = false); + +// \brief Make a delaying source that is optionally noisy (prints when it emits) +AsyncGenerator> MakeDelayedGen(BatchesWithSchema src, + std::string label, + double delay_sec, + bool noisy = false); + +/// A node that slightly resequences the input at random +struct JitterNodeOptions : public ExecNodeOptions { + random::SeedType seed; + /// The max amount to add to a node's "cost". + int max_jitter_modifier; + + explicit JitterNodeOptions(random::SeedType seed, int max_jitter_modifier = 5) + : seed(seed), max_jitter_modifier(max_jitter_modifier) {} + static constexpr std::string_view kName = "jitter"; +}; + +class GateImpl; + +class Gate { + public: + static std::shared_ptr Make(); + + Gate(); + virtual ~Gate(); + + void ReleaseAllBatches(); + void ReleaseOneBatch(); + Future<> WaitForNextReleasedBatch(); + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(Gate); + + GateImpl* impl_; +}; + +// A node that holds all input batches until a given gate is released +struct GatedNodeOptions : public ExecNodeOptions { + explicit GatedNodeOptions(Gate* gate) : gate(gate) {} + Gate* gate; + + static constexpr std::string_view kName = "gated"; +}; + +void RegisterTestNodes(); + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/time_series_util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/time_series_util.h new file mode 100644 index 0000000000000000000000000000000000000000..97707f43bf20b95387f463a9c07e37f54c33998c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/time_series_util.h @@ -0,0 +1,31 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/record_batch.h" +#include "arrow/type_traits.h" + +namespace arrow::acero { + +// normalize the value to unsigned 64-bits while preserving ordering of values +template ::value, bool> = true> +uint64_t NormalizeTime(T t); + +uint64_t GetTime(const RecordBatch* batch, Type::type time_type, int col, uint64_t row); + +} // namespace arrow::acero diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/tpch_node.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/tpch_node.h new file mode 100644 index 0000000000000000000000000000000000000000..e6476b57ad6b4108af56777c029d932f4af94726 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/tpch_node.h @@ -0,0 +1,65 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/acero/type_fwd.h" +#include "arrow/acero/visibility.h" +#include "arrow/result.h" +#include "arrow/status.h" + +namespace arrow { +namespace acero { +namespace internal { + +class ARROW_ACERO_EXPORT TpchGen { + public: + virtual ~TpchGen() = default; + + /* + * \brief Create a factory for nodes that generate TPC-H data + * + * Note: Individual tables will reference each other. It is important that you only + * create a single TpchGen instance for each plan and then you can create nodes for each + * table from that single TpchGen instance. Note: Every batch will be scheduled as a new + * task using the ExecPlan's scheduler. + */ + static Result> Make( + ExecPlan* plan, double scale_factor = 1.0, int64_t batch_size = 4096, + std::optional seed = std::nullopt); + + // The below methods will create and add an ExecNode to the plan that generates + // data for the desired table. If columns is empty, all columns will be generated. + // The methods return the added ExecNode, which should be used for inputs. + virtual Result Supplier(std::vector columns = {}) = 0; + virtual Result Part(std::vector columns = {}) = 0; + virtual Result PartSupp(std::vector columns = {}) = 0; + virtual Result Customer(std::vector columns = {}) = 0; + virtual Result Orders(std::vector columns = {}) = 0; + virtual Result Lineitem(std::vector columns = {}) = 0; + virtual Result Nation(std::vector columns = {}) = 0; + virtual Result Region(std::vector columns = {}) = 0; +}; + +} // namespace internal +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/type_fwd.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..f0410de9f7830a7d0e55a04eb514ae9d82e6958c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/type_fwd.h @@ -0,0 +1,36 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/compute/type_fwd.h" + +namespace arrow { + +namespace acero { + +class ExecNode; +class ExecPlan; +class ExecNodeOptions; +class ExecFactoryRegistry; +class QueryContext; +struct QueryOptions; +struct Declaration; +class SinkNodeConsumer; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/util.h new file mode 100644 index 0000000000000000000000000000000000000000..ee46e8527422abae4f97804058639593dd6b159c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/util.h @@ -0,0 +1,184 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/acero/options.h" +#include "arrow/acero/type_fwd.h" +#include "arrow/buffer.h" +#include "arrow/compute/expression.h" +#include "arrow/compute/util.h" +#include "arrow/memory_pool.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/cpu_info.h" +#include "arrow/util/logging.h" +#include "arrow/util/mutex.h" +#include "arrow/util/thread_pool.h" +#include "arrow/util/type_fwd.h" + +namespace arrow { + +namespace acero { + +ARROW_ACERO_EXPORT +Status ValidateExecNodeInputs(ExecPlan* plan, const std::vector& inputs, + int expected_num_inputs, const char* kind_name); + +ARROW_ACERO_EXPORT +Result> TableFromExecBatches( + const std::shared_ptr& schema, const std::vector& exec_batches); + +class ARROW_ACERO_EXPORT AtomicCounter { + public: + AtomicCounter() = default; + + int count() const { return count_.load(); } + + std::optional total() const { + int total = total_.load(); + if (total == -1) return {}; + return total; + } + + // return true if the counter is complete + bool Increment() { + ARROW_DCHECK_NE(count_.load(), total_.load()); + int count = count_.fetch_add(1) + 1; + if (count != total_.load()) return false; + return DoneOnce(); + } + + // return true if the counter is complete + bool SetTotal(int total) { + total_.store(total); + if (count_.load() != total) return false; + return DoneOnce(); + } + + // return true if the counter has not already been completed + bool Cancel() { return DoneOnce(); } + + // return true if the counter has finished or been cancelled + bool Completed() { return complete_.load(); } + + private: + // ensure there is only one true return from Increment(), SetTotal(), or Cancel() + bool DoneOnce() { + bool expected = false; + return complete_.compare_exchange_strong(expected, true); + } + + std::atomic count_{0}, total_{-1}; + std::atomic complete_{false}; +}; + +class ARROW_ACERO_EXPORT ThreadIndexer { + public: + size_t operator()(); + + static size_t Capacity(); + + private: + static size_t Check(size_t thread_index); + + arrow::util::Mutex mutex_; + std::unordered_map id_to_index_; +}; + +/// \brief A consumer that collects results into an in-memory table +struct ARROW_ACERO_EXPORT TableSinkNodeConsumer : public SinkNodeConsumer { + public: + TableSinkNodeConsumer(std::shared_ptr
* out, MemoryPool* pool) + : out_(out), pool_(pool) {} + Status Init(const std::shared_ptr& schema, + BackpressureControl* backpressure_control, ExecPlan* plan) override; + Status Consume(ExecBatch batch) override; + Future<> Finish() override; + + private: + std::shared_ptr
* out_; + MemoryPool* pool_; + std::shared_ptr schema_; + std::vector> batches_; + arrow::util::Mutex consume_mutex_; +}; + +class ARROW_ACERO_EXPORT NullSinkNodeConsumer : public SinkNodeConsumer { + public: + Status Init(const std::shared_ptr&, BackpressureControl*, + ExecPlan* plan) override { + return Status::OK(); + } + Status Consume(ExecBatch exec_batch) override { return Status::OK(); } + Future<> Finish() override { return Status::OK(); } + + public: + static std::shared_ptr Make() { + return std::make_shared(); + } +}; + +/// CRTP helper for tracing helper functions + +class ARROW_ACERO_EXPORT TracedNode { + public: + // All nodes should call TraceStartProducing or NoteStartProducing exactly once + // Most nodes will be fine with a call to NoteStartProducing since the StartProducing + // call is usually fairly cheap and simply schedules tasks to fetch the actual data. + + explicit TracedNode(ExecNode* node) : node_(node) {} + + // Create a span to record the StartProducing work + [[nodiscard]] ::arrow::internal::tracing::Scope TraceStartProducing( + std::string extra_details) const; + + // Record a call to StartProducing without creating with a span + void NoteStartProducing(std::string extra_details) const; + + // All nodes should call TraceInputReceived for each batch they receive. This call + // should track the time spent processing the batch. NoteInputReceived is available + // but usually won't be used unless a node is simply adding batches to a trivial queue. + + // Create a span to record the InputReceived work + [[nodiscard]] ::arrow::internal::tracing::Scope TraceInputReceived( + const ExecBatch& batch) const; + + // Record a call to InputReceived without creating with a span + void NoteInputReceived(const ExecBatch& batch) const; + + // Create a span to record any "finish" work. This should NOT be called as part of + // InputFinished and many nodes may not need to call this at all. This should be used + // when a node has some extra work that has to be done once it has received all of its + // data. For example, an aggregation node calculating aggregations. This will + // typically be called as a result of InputFinished OR InputReceived. + [[nodiscard]] ::arrow::internal::tracing::Scope TraceFinish() const; + + private: + ExecNode* node_; +}; + +} // namespace acero +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/visibility.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/visibility.h new file mode 100644 index 0000000000000000000000000000000000000000..21a697a56eca962602b34b2766d74442d185c3d7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/acero/visibility.h @@ -0,0 +1,50 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) +# if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +# else +# pragma GCC diagnostic ignored "-Wattributes" +# endif + +# ifdef ARROW_ACERO_STATIC +# define ARROW_ACERO_EXPORT +# elif defined(ARROW_ACERO_EXPORTING) +# define ARROW_ACERO_EXPORT __declspec(dllexport) +# else +# define ARROW_ACERO_EXPORT __declspec(dllimport) +# endif + +# define ARROW_ACERO_NO_EXPORT +#else // Not Windows +# ifndef ARROW_ACERO_EXPORT +# define ARROW_ACERO_EXPORT __attribute__((visibility("default"))) +# endif +# ifndef ARROW_ACERO_NO_EXPORT +# define ARROW_ACERO_NO_EXPORT __attribute__((visibility("hidden"))) +# endif +#endif // Not-Windows + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/api.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/api.h new file mode 100644 index 0000000000000000000000000000000000000000..ac568a00eedc32984758f4675b58ac626c9c947a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/api.h @@ -0,0 +1,47 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Coarse public API while the library is in development + +#pragma once + +#include "arrow/array.h" // IWYU pragma: export +#include "arrow/array/array_run_end.h" // IWYU pragma: export +#include "arrow/array/concatenate.h" // IWYU pragma: export +#include "arrow/buffer.h" // IWYU pragma: export +#include "arrow/builder.h" // IWYU pragma: export +#include "arrow/chunked_array.h" // IWYU pragma: export +#include "arrow/compare.h" // IWYU pragma: export +#include "arrow/config.h" // IWYU pragma: export +#include "arrow/datum.h" // IWYU pragma: export +#include "arrow/extension_type.h" // IWYU pragma: export +#include "arrow/memory_pool.h" // IWYU pragma: export +#include "arrow/pretty_print.h" // IWYU pragma: export +#include "arrow/record_batch.h" // IWYU pragma: export +#include "arrow/result.h" // IWYU pragma: export +#include "arrow/status.h" // IWYU pragma: export +#include "arrow/table.h" // IWYU pragma: export +#include "arrow/table_builder.h" // IWYU pragma: export +#include "arrow/tensor.h" // IWYU pragma: export +#include "arrow/type.h" // IWYU pragma: export +#include "arrow/util/key_value_metadata.h" // IWYU pragma: export +#include "arrow/visit_array_inline.h" // IWYU pragma: export +#include "arrow/visit_scalar_inline.h" // IWYU pragma: export +#include "arrow/visitor.h" // IWYU pragma: export + +/// \brief Top-level namespace for Apache Arrow C++ API +namespace arrow {} diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array.h new file mode 100644 index 0000000000000000000000000000000000000000..4d72ea9506a414fd6e50d5c7d0af437084045e05 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array.h @@ -0,0 +1,49 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Kitchen-sink public API for arrow::Array data structures. C++ library code +// (especially header files) in Apache Arrow should use more specific headers +// unless it's a file that uses most or all Array types in which case using +// arrow/array.h is fine. + +#pragma once + +/// \defgroup numeric-arrays Concrete classes for numeric arrays +/// @{ +/// @} + +/// \defgroup binary-arrays Concrete classes for binary/string arrays +/// @{ +/// @} + +/// \defgroup nested-arrays Concrete classes for nested arrays +/// @{ +/// @} + +/// \defgroup run-end-encoded-arrays Concrete classes for run-end encoded arrays +/// @{ +/// @} + +#include "arrow/array/array_base.h" // IWYU pragma: keep +#include "arrow/array/array_binary.h" // IWYU pragma: keep +#include "arrow/array/array_decimal.h" // IWYU pragma: keep +#include "arrow/array/array_dict.h" // IWYU pragma: keep +#include "arrow/array/array_nested.h" // IWYU pragma: keep +#include "arrow/array/array_primitive.h" // IWYU pragma: keep +#include "arrow/array/array_run_end.h" // IWYU pragma: keep +#include "arrow/array/data.h" // IWYU pragma: keep +#include "arrow/array/util.h" // IWYU pragma: keep diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_base.h new file mode 100644 index 0000000000000000000000000000000000000000..60df45357e5d2fd8bc31cfa714aa4d9d89288508 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_base.h @@ -0,0 +1,323 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/array/data.h" +#include "arrow/buffer.h" +#include "arrow/compare.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" +#include "arrow/visitor.h" + +namespace arrow { + +// ---------------------------------------------------------------------- +// User array accessor types + +/// \brief Array base type +/// Immutable data array with some logical type and some length. +/// +/// Any memory is owned by the respective Buffer instance (or its parents). +/// +/// The base class is only required to have a null bitmap buffer if the null +/// count is greater than 0 +/// +/// If known, the null count can be provided in the base Array constructor. If +/// the null count is not known, pass -1 to indicate that the null count is to +/// be computed on the first call to null_count() +class ARROW_EXPORT Array { + public: + virtual ~Array() = default; + + /// \brief Return true if value at index is null. Does not boundscheck + bool IsNull(int64_t i) const { return !IsValid(i); } + + /// \brief Return true if value at index is valid (not null). Does not + /// boundscheck + bool IsValid(int64_t i) const { + if (null_bitmap_data_ != NULLPTR) { + return bit_util::GetBit(null_bitmap_data_, i + data_->offset); + } + // Dispatching with a few conditionals like this makes IsNull more + // efficient for how it is used in practice. Making IsNull virtual + // would add a vtable lookup to every call and prevent inlining + + // a potential inner-branch removal. + if (type_id() == Type::SPARSE_UNION) { + return !internal::IsNullSparseUnion(*data_, i); + } + if (type_id() == Type::DENSE_UNION) { + return !internal::IsNullDenseUnion(*data_, i); + } + if (type_id() == Type::RUN_END_ENCODED) { + return !internal::IsNullRunEndEncoded(*data_, i); + } + return data_->null_count != data_->length; + } + + /// \brief Return a Scalar containing the value of this array at i + Result> GetScalar(int64_t i) const; + + /// Size in the number of elements this array contains. + int64_t length() const { return data_->length; } + + /// A relative position into another array's data, to enable zero-copy + /// slicing. This value defaults to zero + int64_t offset() const { return data_->offset; } + + /// The number of null entries in the array. If the null count was not known + /// at time of construction (and set to a negative value), then the null + /// count will be computed and cached on the first invocation of this + /// function + int64_t null_count() const; + + /// \brief Computes the logical null count for arrays of all types including + /// those that do not have a validity bitmap like union and run-end encoded + /// arrays + /// + /// If the array has a validity bitmap, this function behaves the same as + /// null_count(). For types that have no validity bitmap, this function will + /// recompute the null count every time it is called. + /// + /// \see GetNullCount + int64_t ComputeLogicalNullCount() const; + + const std::shared_ptr& type() const { return data_->type; } + Type::type type_id() const { return data_->type->id(); } + + /// Buffer for the validity (null) bitmap, if any. Note that Union types + /// never have a null bitmap. + /// + /// Note that for `null_count == 0` or for null type, this will be null. + /// This buffer does not account for any slice offset + const std::shared_ptr& null_bitmap() const { return data_->buffers[0]; } + + /// Raw pointer to the null bitmap. + /// + /// Note that for `null_count == 0` or for null type, this will be null. + /// This buffer does not account for any slice offset + const uint8_t* null_bitmap_data() const { return null_bitmap_data_; } + + /// Equality comparison with another array + /// + /// Note that arrow::ArrayStatistics is not included in the comparison. + bool Equals(const Array& arr, const EqualOptions& = EqualOptions::Defaults()) const; + bool Equals(const std::shared_ptr& arr, + const EqualOptions& = EqualOptions::Defaults()) const; + + /// \brief Return the formatted unified diff of arrow::Diff between this + /// Array and another Array + std::string Diff(const Array& other) const; + + /// Approximate equality comparison with another array + /// + /// epsilon is only used if this is FloatArray or DoubleArray + /// + /// Note that arrow::ArrayStatistics is not included in the comparison. + bool ApproxEquals(const std::shared_ptr& arr, + const EqualOptions& = EqualOptions::Defaults()) const; + bool ApproxEquals(const Array& arr, + const EqualOptions& = EqualOptions::Defaults()) const; + + /// Compare if the range of slots specified are equal for the given array and + /// this array. end_idx exclusive. This methods does not bounds check. + /// + /// Note that arrow::ArrayStatistics is not included in the comparison. + bool RangeEquals(int64_t start_idx, int64_t end_idx, int64_t other_start_idx, + const Array& other, + const EqualOptions& = EqualOptions::Defaults()) const; + bool RangeEquals(int64_t start_idx, int64_t end_idx, int64_t other_start_idx, + const std::shared_ptr& other, + const EqualOptions& = EqualOptions::Defaults()) const; + bool RangeEquals(const Array& other, int64_t start_idx, int64_t end_idx, + int64_t other_start_idx, + const EqualOptions& = EqualOptions::Defaults()) const; + bool RangeEquals(const std::shared_ptr& other, int64_t start_idx, + int64_t end_idx, int64_t other_start_idx, + const EqualOptions& = EqualOptions::Defaults()) const; + + /// \brief Apply the ArrayVisitor::Visit() method specialized to the array type + Status Accept(ArrayVisitor* visitor) const; + + /// Construct a zero-copy view of this array with the given type. + /// + /// This method checks if the types are layout-compatible. + /// Nested types are traversed in depth-first order. Data buffers must have + /// the same item sizes, even though the logical types may be different. + /// An error is returned if the types are not layout-compatible. + Result> View(const std::shared_ptr& type) const; + + /// \brief Construct a copy of the array with all buffers on destination + /// Memory Manager + /// + /// This method recursively copies the array's buffers and those of its children + /// onto the destination MemoryManager device and returns the new Array. + Result> CopyTo(const std::shared_ptr& to) const; + + /// \brief Construct a new array attempting to zero-copy view if possible. + /// + /// Like CopyTo this method recursively goes through all of the array's buffers + /// and those of it's children and first attempts to create zero-copy + /// views on the destination MemoryManager device. If it can't, it falls back + /// to performing a copy. See Buffer::ViewOrCopy. + Result> ViewOrCopyTo( + const std::shared_ptr& to) const; + + /// Construct a zero-copy slice of the array with the indicated offset and + /// length + /// + /// \param[in] offset the position of the first element in the constructed + /// slice + /// \param[in] length the length of the slice. If there are not enough + /// elements in the array, the length will be adjusted accordingly + /// + /// \return a new object wrapped in std::shared_ptr + std::shared_ptr Slice(int64_t offset, int64_t length) const; + + /// Slice from offset until end of the array + std::shared_ptr Slice(int64_t offset) const; + + /// Input-checking variant of Array::Slice + Result> SliceSafe(int64_t offset, int64_t length) const; + /// Input-checking variant of Array::Slice + Result> SliceSafe(int64_t offset) const; + + const std::shared_ptr& data() const { return data_; } + + int num_fields() const { return static_cast(data_->child_data.size()); } + + /// \return PrettyPrint representation of array suitable for debugging + std::string ToString() const; + + /// \brief Perform cheap validation checks to determine obvious inconsistencies + /// within the array's internal data. + /// + /// This is O(k) where k is the number of descendents. + /// + /// \return Status + Status Validate() const; + + /// \brief Perform extensive validation checks to determine inconsistencies + /// within the array's internal data. + /// + /// This is potentially O(k*n) where k is the number of descendents and n + /// is the array length. + /// + /// \return Status + Status ValidateFull() const; + + /// \brief Return the device_type that this array's data is allocated on + /// + /// This just delegates to calling device_type on the underlying ArrayData + /// object which backs this Array. + /// + /// \return DeviceAllocationType + DeviceAllocationType device_type() const { return data_->device_type(); } + + /// \brief Return the statistics of this Array + /// + /// This just delegates to calling statistics on the underlying ArrayData + /// object which backs this Array. + /// + /// \return const std::shared_ptr& + const std::shared_ptr& statistics() const { return data_->statistics; } + + protected: + Array() = default; + ARROW_DEFAULT_MOVE_AND_ASSIGN(Array); + + std::shared_ptr data_; + const uint8_t* null_bitmap_data_ = NULLPTR; + + /// Protected method for constructors + void SetData(const std::shared_ptr& data) { + if (data->buffers.size() > 0) { + null_bitmap_data_ = data->GetValuesSafe(0, /*offset=*/0); + } else { + null_bitmap_data_ = NULLPTR; + } + data_ = data; + } + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(Array); +}; + +ARROW_EXPORT void PrintTo(const Array& x, std::ostream* os); + +static inline std::ostream& operator<<(std::ostream& os, const Array& x) { + os << x.ToString(); + return os; +} + +/// Base class for non-nested arrays +class ARROW_EXPORT FlatArray : public Array { + protected: + using Array::Array; +}; + +/// Base class for arrays of fixed-size logical types +class ARROW_EXPORT PrimitiveArray : public FlatArray { + public: + /// Does not account for any slice offset + const std::shared_ptr& values() const { return data_->buffers[1]; } + + protected: + PrimitiveArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + PrimitiveArray() : raw_values_(NULLPTR) {} + + void SetData(const std::shared_ptr& data) { + this->Array::SetData(data); + raw_values_ = data->GetValuesSafe(1, /*offset=*/0); + } + + explicit PrimitiveArray(const std::shared_ptr& data) { SetData(data); } + + const uint8_t* raw_values_; +}; + +/// Degenerate null type Array +class ARROW_EXPORT NullArray : public FlatArray { + public: + using TypeClass = NullType; + + explicit NullArray(const std::shared_ptr& data) { SetData(data); } + explicit NullArray(int64_t length); + + private: + void SetData(const std::shared_ptr& data) { + null_bitmap_data_ = NULLPTR; + data->null_count = data->length; + data_ = data; + } +}; + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_binary.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_binary.h new file mode 100644 index 0000000000000000000000000000000000000000..63903eac46d413c24ccaeb048273e8f5e6c8d3c6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_binary.h @@ -0,0 +1,321 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Array accessor classes for Binary, LargeBinary, String, LargeString, +// FixedSizeBinary + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/data.h" +#include "arrow/buffer.h" +#include "arrow/stl_iterator.h" +#include "arrow/type.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup binary-arrays +/// +/// @{ + +// ---------------------------------------------------------------------- +// Binary and String + +/// Base class for variable-sized binary arrays, regardless of offset size +/// and logical interpretation. +template +class BaseBinaryArray : public FlatArray { + public: + using TypeClass = TYPE; + using offset_type = typename TypeClass::offset_type; + using IteratorType = stl::ArrayIterator>; + + /// Return the pointer to the given elements bytes + // XXX should GetValue(int64_t i) return a string_view? + const uint8_t* GetValue(int64_t i, offset_type* out_length) const { + const offset_type pos = raw_value_offsets_[i]; + *out_length = raw_value_offsets_[i + 1] - pos; + return raw_data_ + pos; + } + + /// \brief Get binary value as a string_view + /// + /// \param i the value index + /// \return the view over the selected value + std::string_view GetView(int64_t i) const { + const offset_type pos = raw_value_offsets_[i]; + return std::string_view(reinterpret_cast(raw_data_ + pos), + raw_value_offsets_[i + 1] - pos); + } + + std::optional operator[](int64_t i) const { + return *IteratorType(*this, i); + } + + /// \brief Get binary value as a string_view + /// Provided for consistency with other arrays. + /// + /// \param i the value index + /// \return the view over the selected value + std::string_view Value(int64_t i) const { return GetView(i); } + + /// \brief Get binary value as a std::string + /// + /// \param i the value index + /// \return the value copied into a std::string + std::string GetString(int64_t i) const { return std::string(GetView(i)); } + + /// Note that this buffer does not account for any slice offset + std::shared_ptr value_offsets() const { return data_->buffers[1]; } + + /// Note that this buffer does not account for any slice offset + std::shared_ptr value_data() const { return data_->buffers[2]; } + + const offset_type* raw_value_offsets() const { return raw_value_offsets_; } + + const uint8_t* raw_data() const { return raw_data_; } + + /// \brief Return the data buffer absolute offset of the data for the value + /// at the passed index. + /// + /// Does not perform boundschecking + offset_type value_offset(int64_t i) const { return raw_value_offsets_[i]; } + + /// \brief Return the length of the data for the value at the passed index. + /// + /// Does not perform boundschecking + offset_type value_length(int64_t i) const { + return raw_value_offsets_[i + 1] - raw_value_offsets_[i]; + } + + /// \brief Return the total length of the memory in the data buffer + /// referenced by this array. If the array has been sliced then this may be + /// less than the size of the data buffer (data_->buffers[2]). + offset_type total_values_length() const { + if (data_->length > 0) { + return raw_value_offsets_[data_->length] - raw_value_offsets_[0]; + } else { + return 0; + } + } + + IteratorType begin() const { return IteratorType(*this); } + + IteratorType end() const { return IteratorType(*this, length()); } + + protected: + // For subclasses + BaseBinaryArray() = default; + + // Protected method for constructors + void SetData(const std::shared_ptr& data) { + this->Array::SetData(data); + raw_value_offsets_ = data->GetValuesSafe(1); + raw_data_ = data->GetValuesSafe(2, /*offset=*/0); + } + + const offset_type* raw_value_offsets_ = NULLPTR; + const uint8_t* raw_data_ = NULLPTR; +}; + +/// Concrete Array class for variable-size binary data +class ARROW_EXPORT BinaryArray : public BaseBinaryArray { + public: + explicit BinaryArray(const std::shared_ptr& data); + + BinaryArray(int64_t length, const std::shared_ptr& value_offsets, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + protected: + // For subclasses such as StringArray + BinaryArray() : BaseBinaryArray() {} +}; + +/// Concrete Array class for variable-size string (utf-8) data +class ARROW_EXPORT StringArray : public BinaryArray { + public: + using TypeClass = StringType; + + explicit StringArray(const std::shared_ptr& data); + + StringArray(int64_t length, const std::shared_ptr& value_offsets, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Validate that this array contains only valid UTF8 entries + /// + /// This check is also implied by ValidateFull() + Status ValidateUTF8() const; +}; + +/// Concrete Array class for large variable-size binary data +class ARROW_EXPORT LargeBinaryArray : public BaseBinaryArray { + public: + explicit LargeBinaryArray(const std::shared_ptr& data); + + LargeBinaryArray(int64_t length, const std::shared_ptr& value_offsets, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + protected: + // For subclasses such as LargeStringArray + LargeBinaryArray() : BaseBinaryArray() {} +}; + +/// Concrete Array class for large variable-size string (utf-8) data +class ARROW_EXPORT LargeStringArray : public LargeBinaryArray { + public: + using TypeClass = LargeStringType; + + explicit LargeStringArray(const std::shared_ptr& data); + + LargeStringArray(int64_t length, const std::shared_ptr& value_offsets, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Validate that this array contains only valid UTF8 entries + /// + /// This check is also implied by ValidateFull() + Status ValidateUTF8() const; +}; + +// ---------------------------------------------------------------------- +// BinaryView and StringView + +/// Concrete Array class for variable-size binary view data using the +/// BinaryViewType::c_type struct to reference in-line or out-of-line string values +class ARROW_EXPORT BinaryViewArray : public FlatArray { + public: + using TypeClass = BinaryViewType; + using IteratorType = stl::ArrayIterator; + using c_type = BinaryViewType::c_type; + + explicit BinaryViewArray(std::shared_ptr data); + + BinaryViewArray(std::shared_ptr type, int64_t length, + std::shared_ptr views, BufferVector data_buffers, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + // For API compatibility with BinaryArray etc. + std::string_view GetView(int64_t i) const; + std::string GetString(int64_t i) const { return std::string{GetView(i)}; } + + const auto& values() const { return data_->buffers[1]; } + const c_type* raw_values() const { return raw_values_; } + + std::optional operator[](int64_t i) const { + return *IteratorType(*this, i); + } + + IteratorType begin() const { return IteratorType(*this); } + IteratorType end() const { return IteratorType(*this, length()); } + + protected: + using FlatArray::FlatArray; + + void SetData(std::shared_ptr data) { + FlatArray::SetData(std::move(data)); + raw_values_ = data_->GetValuesSafe(1); + } + + const c_type* raw_values_; +}; + +/// Concrete Array class for variable-size string view (utf-8) data using +/// BinaryViewType::c_type to reference in-line or out-of-line string values +class ARROW_EXPORT StringViewArray : public BinaryViewArray { + public: + using TypeClass = StringViewType; + + explicit StringViewArray(std::shared_ptr data); + + using BinaryViewArray::BinaryViewArray; + + /// \brief Validate that this array contains only valid UTF8 entries + /// + /// This check is also implied by ValidateFull() + Status ValidateUTF8() const; +}; + +// ---------------------------------------------------------------------- +// Fixed width binary + +/// Concrete Array class for fixed-size binary data +class ARROW_EXPORT FixedSizeBinaryArray : public PrimitiveArray { + public: + using TypeClass = FixedSizeBinaryType; + using IteratorType = stl::ArrayIterator; + + explicit FixedSizeBinaryArray(const std::shared_ptr& data); + + FixedSizeBinaryArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + const uint8_t* GetValue(int64_t i) const { return values_ + i * byte_width_; } + const uint8_t* Value(int64_t i) const { return GetValue(i); } + + std::string_view GetView(int64_t i) const { + return std::string_view(reinterpret_cast(GetValue(i)), byte_width_); + } + + std::optional operator[](int64_t i) const { + return *IteratorType(*this, i); + } + + std::string GetString(int64_t i) const { return std::string(GetView(i)); } + + int32_t byte_width() const { return byte_width_; } + + const uint8_t* raw_values() const { return values_; } + + IteratorType begin() const { return IteratorType(*this); } + + IteratorType end() const { return IteratorType(*this, length()); } + + protected: + void SetData(const std::shared_ptr& data) { + this->PrimitiveArray::SetData(data); + byte_width_ = + internal::checked_cast(*type()).byte_width(); + values_ = raw_values_ + data_->offset * byte_width_; + } + + const uint8_t* values_; + int32_t byte_width_; +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_decimal.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_decimal.h new file mode 100644 index 0000000000000000000000000000000000000000..2f10bb842999640a8cada703ff12ea29c0e5f718 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_decimal.h @@ -0,0 +1,104 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/array/array_binary.h" +#include "arrow/array/data.h" +#include "arrow/type.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup numeric-arrays +/// +/// @{ + +// ---------------------------------------------------------------------- +// Decimal32Array + +/// Concrete Array class for 32-bit decimal data +class ARROW_EXPORT Decimal32Array : public FixedSizeBinaryArray { + public: + using TypeClass = Decimal32Type; + + using FixedSizeBinaryArray::FixedSizeBinaryArray; + + /// \brief Construct Decimal32Array from ArrayData instance + explicit Decimal32Array(const std::shared_ptr& data); + + std::string FormatValue(int64_t i) const; +}; + +// ---------------------------------------------------------------------- +// Decimal64Array + +/// Concrete Array class for 64-bit decimal data +class ARROW_EXPORT Decimal64Array : public FixedSizeBinaryArray { + public: + using TypeClass = Decimal64Type; + + using FixedSizeBinaryArray::FixedSizeBinaryArray; + + /// \brief Construct Decimal64Array from ArrayData instance + explicit Decimal64Array(const std::shared_ptr& data); + + std::string FormatValue(int64_t i) const; +}; + +// ---------------------------------------------------------------------- +// Decimal128Array + +/// Concrete Array class for 128-bit decimal data +class ARROW_EXPORT Decimal128Array : public FixedSizeBinaryArray { + public: + using TypeClass = Decimal128Type; + + using FixedSizeBinaryArray::FixedSizeBinaryArray; + + /// \brief Construct Decimal128Array from ArrayData instance + explicit Decimal128Array(const std::shared_ptr& data); + + std::string FormatValue(int64_t i) const; +}; + +// Backward compatibility +using DecimalArray = Decimal128Array; + +// ---------------------------------------------------------------------- +// Decimal256Array + +/// Concrete Array class for 256-bit decimal data +class ARROW_EXPORT Decimal256Array : public FixedSizeBinaryArray { + public: + using TypeClass = Decimal256Type; + + using FixedSizeBinaryArray::FixedSizeBinaryArray; + + /// \brief Construct Decimal256Array from ArrayData instance + explicit Decimal256Array(const std::shared_ptr& data); + + std::string FormatValue(int64_t i) const; +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_dict.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_dict.h new file mode 100644 index 0000000000000000000000000000000000000000..bf376b51f8c9470d2b4e4c7ed950c9a513fddc9b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_dict.h @@ -0,0 +1,182 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/data.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +// ---------------------------------------------------------------------- +// DictionaryArray + +/// \brief Array type for dictionary-encoded data with a +/// data-dependent dictionary +/// +/// A dictionary array contains an array of non-negative integers (the +/// "dictionary indices") along with a data type containing a "dictionary" +/// corresponding to the distinct values represented in the data. +/// +/// For example, the array +/// +/// ["foo", "bar", "foo", "bar", "foo", "bar"] +/// +/// with dictionary ["bar", "foo"], would have dictionary array representation +/// +/// indices: [1, 0, 1, 0, 1, 0] +/// dictionary: ["bar", "foo"] +/// +/// The indices in principle may be any integer type. +class ARROW_EXPORT DictionaryArray : public Array { + public: + using TypeClass = DictionaryType; + + explicit DictionaryArray(const std::shared_ptr& data); + + DictionaryArray(const std::shared_ptr& type, + const std::shared_ptr& indices, + const std::shared_ptr& dictionary); + + /// \brief Construct DictionaryArray from dictionary and indices + /// array and validate + /// + /// This function does the validation of the indices and input type. It checks if + /// all indices are non-negative and smaller than the size of the dictionary. + /// + /// \param[in] type a dictionary type + /// \param[in] dictionary the dictionary with same value type as the + /// type object + /// \param[in] indices an array of non-negative integers smaller than the + /// size of the dictionary + static Result> FromArrays( + const std::shared_ptr& type, const std::shared_ptr& indices, + const std::shared_ptr& dictionary); + + static Result> FromArrays( + const std::shared_ptr& indices, const std::shared_ptr& dictionary) { + return FromArrays(::arrow::dictionary(indices->type(), dictionary->type()), indices, + dictionary); + } + + /// \brief Transpose this DictionaryArray + /// + /// This method constructs a new dictionary array with the given dictionary + /// type, transposing indices using the transpose map. The type and the + /// transpose map are typically computed using DictionaryUnifier. + /// + /// \param[in] type the new type object + /// \param[in] dictionary the new dictionary + /// \param[in] transpose_map transposition array of this array's indices + /// into the target array's indices + /// \param[in] pool a pool to allocate the array data from + Result> Transpose( + const std::shared_ptr& type, const std::shared_ptr& dictionary, + const int32_t* transpose_map, MemoryPool* pool = default_memory_pool()) const; + + Result> Compact(MemoryPool* pool = default_memory_pool()) const; + + /// \brief Determine whether dictionary arrays may be compared without unification + bool CanCompareIndices(const DictionaryArray& other) const; + + /// \brief Return the dictionary for this array, which is stored as + /// a member of the ArrayData internal structure + const std::shared_ptr& dictionary() const; + const std::shared_ptr& indices() const; + + /// \brief Return the ith value of indices, cast to int64_t. Not recommended + /// for use in performance-sensitive code. Does not validate whether the + /// value is null or out-of-bounds. + int64_t GetValueIndex(int64_t i) const; + + const DictionaryType* dict_type() const { return dict_type_; } + + private: + void SetData(const std::shared_ptr& data); + const DictionaryType* dict_type_; + std::shared_ptr indices_; + + // Lazily initialized when invoking dictionary() + mutable std::shared_ptr dictionary_; +}; + +/// \brief Helper class for incremental dictionary unification +class ARROW_EXPORT DictionaryUnifier { + public: + virtual ~DictionaryUnifier() = default; + + /// \brief Construct a DictionaryUnifier + /// \param[in] value_type the data type of the dictionaries + /// \param[in] pool MemoryPool to use for memory allocations + static Result> Make( + std::shared_ptr value_type, MemoryPool* pool = default_memory_pool()); + + /// \brief Unify dictionaries across array chunks + /// + /// The dictionaries in the array chunks will be unified, their indices + /// accordingly transposed. + /// + /// Only dictionaries with a primitive value type are currently supported. + /// However, dictionaries nested inside a more complex type are correctly unified. + static Result> UnifyChunkedArray( + const std::shared_ptr& array, + MemoryPool* pool = default_memory_pool()); + + /// \brief Unify dictionaries across the chunks of each table column + /// + /// The dictionaries in each table column will be unified, their indices + /// accordingly transposed. + /// + /// Only dictionaries with a primitive value type are currently supported. + /// However, dictionaries nested inside a more complex type are correctly unified. + static Result> UnifyTable( + const Table& table, MemoryPool* pool = default_memory_pool()); + + /// \brief Append dictionary to the internal memo + virtual Status Unify(const Array& dictionary) = 0; + + /// \brief Append dictionary and compute transpose indices + /// \param[in] dictionary the dictionary values to unify + /// \param[out] out_transpose a Buffer containing computed transpose indices + /// as int32_t values equal in length to the passed dictionary. The value in + /// each slot corresponds to the new index value for each original index + /// for a DictionaryArray with the old dictionary + virtual Status Unify(const Array& dictionary, + std::shared_ptr* out_transpose) = 0; + + /// \brief Return a result DictionaryType with the smallest possible index + /// type to accommodate the unified dictionary. The unifier cannot be used + /// after this is called + virtual Status GetResult(std::shared_ptr* out_type, + std::shared_ptr* out_dict) = 0; + + /// \brief Return a unified dictionary with the given index type. If + /// the index type is not large enough then an invalid status will be returned. + /// The unifier cannot be used after this is called + virtual Status GetResultWithIndexType(const std::shared_ptr& index_type, + std::shared_ptr* out_dict) = 0; +}; + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_nested.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_nested.h new file mode 100644 index 0000000000000000000000000000000000000000..bf84f802b1ab502fc50794997645b52756bb6df2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_nested.h @@ -0,0 +1,899 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Array accessor classes for List, LargeList, ListView, LargeListView, FixedSizeList, +// Map, Struct, and Union + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/data.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_fwd.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup nested-arrays +/// +/// @{ + +// ---------------------------------------------------------------------- +// VarLengthListLikeArray + +template +class VarLengthListLikeArray; + +namespace internal { + +// Private helper for [Large]List[View]Array::SetData. +// Unfortunately, trying to define VarLengthListLikeArray::SetData outside of this header +// doesn't play well with MSVC. +template +void SetListData(VarLengthListLikeArray* self, + const std::shared_ptr& data, + Type::type expected_type_id = TYPE::type_id); + +/// \brief A version of Flatten that keeps recursively flattening until an array of +/// non-list values is reached. +/// +/// Array types considered to be lists by this function: +/// - list +/// - large_list +/// - list_view +/// - large_list_view +/// - fixed_size_list +/// +/// \see ListArray::Flatten +ARROW_EXPORT Result> FlattenLogicalListRecursively( + const Array& in_array, MemoryPool* memory_pool); + +} // namespace internal + +/// Base class for variable-sized list and list-view arrays, regardless of offset size. +template +class VarLengthListLikeArray : public Array { + public: + using TypeClass = TYPE; + using offset_type = typename TypeClass::offset_type; + + const TypeClass* var_length_list_like_type() const { return this->list_type_; } + + /// \brief Return array object containing the list's values + /// + /// Note that this buffer does not account for any slice offset or length. + const std::shared_ptr& values() const { return values_; } + + /// Note that this buffer does not account for any slice offset or length. + const std::shared_ptr& value_offsets() const { return data_->buffers[1]; } + + const std::shared_ptr& value_type() const { return list_type_->value_type(); } + + /// Return pointer to raw value offsets accounting for any slice offset + const offset_type* raw_value_offsets() const { return raw_value_offsets_; } + + // The following functions will not perform boundschecking + + offset_type value_offset(int64_t i) const { return raw_value_offsets_[i]; } + + /// \brief Return the size of the value at a particular index + /// + /// Since non-empty null lists and list-views are possible, avoid calling this + /// function when the list at slot i is null. + /// + /// \pre IsValid(i) + virtual offset_type value_length(int64_t i) const = 0; + + /// \pre IsValid(i) + std::shared_ptr value_slice(int64_t i) const { + return values_->Slice(value_offset(i), value_length(i)); + } + + /// \brief Flatten all level recursively until reach a non-list type, and return + /// a non-list type Array. + /// + /// \see internal::FlattenLogicalListRecursively + Result> FlattenRecursively( + MemoryPool* memory_pool = default_memory_pool()) const { + return internal::FlattenLogicalListRecursively(*this, memory_pool); + } + + protected: + friend void internal::SetListData(VarLengthListLikeArray* self, + const std::shared_ptr& data, + Type::type expected_type_id); + + const TypeClass* list_type_ = NULLPTR; + std::shared_ptr values_; + const offset_type* raw_value_offsets_ = NULLPTR; +}; + +// ---------------------------------------------------------------------- +// ListArray / LargeListArray + +template +class BaseListArray : public VarLengthListLikeArray { + public: + using TypeClass = TYPE; + using offset_type = typename TYPE::offset_type; + + const TypeClass* list_type() const { return this->var_length_list_like_type(); } + + /// \brief Return the size of the value at a particular index + /// + /// Since non-empty null lists are possible, avoid calling this + /// function when the list at slot i is null. + /// + /// \pre IsValid(i) + offset_type value_length(int64_t i) const final { + return this->raw_value_offsets_[i + 1] - this->raw_value_offsets_[i]; + } +}; + +/// Concrete Array class for list data +class ARROW_EXPORT ListArray : public BaseListArray { + public: + explicit ListArray(std::shared_ptr data); + + ListArray(std::shared_ptr type, int64_t length, + std::shared_ptr value_offsets, std::shared_ptr values, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Construct ListArray from array of offsets and child value array + /// + /// This function does the bare minimum of validation of the offsets and + /// input types, and will allocate a new offsets array if necessary (i.e. if + /// the offsets contain any nulls). If the offsets do not have nulls, they + /// are assumed to be well-formed. + /// + /// If a null_bitmap is not provided, the nulls will be inferred from the offsets' + /// null bitmap. But if a null_bitmap is provided, the offsets array can't have nulls. + /// + /// And when a null_bitmap is provided, the offsets array cannot be a slice (i.e. an + /// array with offset() > 0). + /// + /// \param[in] offsets Array containing n + 1 offsets encoding length and + /// size. Must be of int32 type + /// \param[in] values Array containing list values + /// \param[in] pool MemoryPool in case new offsets array needs to be + /// allocated because of null values + /// \param[in] null_bitmap Optional validity bitmap + /// \param[in] null_count Optional null count in null_bitmap + static Result> FromArrays( + const Array& offsets, const Array& values, MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + static Result> FromArrays( + std::shared_ptr type, const Array& offsets, const Array& values, + MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + /// \brief Build a ListArray from a ListViewArray + static Result> FromListView(const ListViewArray& source, + MemoryPool* pool); + + /// \brief Return an Array that is a concatenation of the lists in this array. + /// + /// Note that it's different from `values()` in that it takes into + /// consideration of this array's offsets as well as null elements backed + /// by non-empty lists (they are skipped, thus copying may be needed). + Result> Flatten( + MemoryPool* memory_pool = default_memory_pool()) const; + + /// \brief Return list offsets as an Int32Array + /// + /// The returned array will not have a validity bitmap, so you cannot expect + /// to pass it to ListArray::FromArrays() and get back the same list array + /// if the original one has nulls. + std::shared_ptr offsets() const; + + protected: + // This constructor defers SetData to a derived array class + ListArray() = default; + + void SetData(const std::shared_ptr& data); +}; + +/// Concrete Array class for large list data (with 64-bit offsets) +class ARROW_EXPORT LargeListArray : public BaseListArray { + public: + explicit LargeListArray(const std::shared_ptr& data); + + LargeListArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& value_offsets, + const std::shared_ptr& values, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Construct LargeListArray from array of offsets and child value array + /// + /// This function does the bare minimum of validation of the offsets and + /// input types, and will allocate a new offsets array if necessary (i.e. if + /// the offsets contain any nulls). If the offsets do not have nulls, they + /// are assumed to be well-formed. + /// + /// If a null_bitmap is not provided, the nulls will be inferred from the offsets' + /// null bitmap. But if a null_bitmap is provided, the offsets array can't have nulls. + /// + /// And when a null_bitmap is provided, the offsets array cannot be a slice (i.e. an + /// array with offset() > 0). + /// + /// \param[in] offsets Array containing n + 1 offsets encoding length and + /// size. Must be of int64 type + /// \param[in] values Array containing list values + /// \param[in] pool MemoryPool in case new offsets array needs to be + /// allocated because of null values + /// \param[in] null_bitmap Optional validity bitmap + /// \param[in] null_count Optional null count in null_bitmap + static Result> FromArrays( + const Array& offsets, const Array& values, MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + static Result> FromArrays( + std::shared_ptr type, const Array& offsets, const Array& values, + MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + /// \brief Build a LargeListArray from a LargeListViewArray + static Result> FromListView( + const LargeListViewArray& source, MemoryPool* pool); + + /// \brief Return an Array that is a concatenation of the lists in this array. + /// + /// Note that it's different from `values()` in that it takes into + /// consideration of this array's offsets as well as null elements backed + /// by non-empty lists (they are skipped, thus copying may be needed). + Result> Flatten( + MemoryPool* memory_pool = default_memory_pool()) const; + + /// \brief Return list offsets as an Int64Array + std::shared_ptr offsets() const; + + protected: + void SetData(const std::shared_ptr& data); +}; + +// ---------------------------------------------------------------------- +// ListViewArray / LargeListViewArray + +template +class BaseListViewArray : public VarLengthListLikeArray { + public: + using TypeClass = TYPE; + using offset_type = typename TYPE::offset_type; + + const TypeClass* list_view_type() const { return this->var_length_list_like_type(); } + + /// \brief Note that this buffer does not account for any slice offset or length. + const std::shared_ptr& value_sizes() const { return this->data_->buffers[2]; } + + /// \brief Return pointer to raw value offsets accounting for any slice offset + const offset_type* raw_value_sizes() const { return raw_value_sizes_; } + + /// \brief Return the size of the value at a particular index + /// + /// This should not be called if the list-view at slot i is null. + /// The returned size in those cases could be any value from 0 to the + /// length of the child values array. + /// + /// \pre IsValid(i) + offset_type value_length(int64_t i) const final { return this->raw_value_sizes_[i]; } + + protected: + const offset_type* raw_value_sizes_ = NULLPTR; +}; + +/// \brief Concrete Array class for list-view data +class ARROW_EXPORT ListViewArray : public BaseListViewArray { + public: + explicit ListViewArray(std::shared_ptr data); + + ListViewArray(std::shared_ptr type, int64_t length, + std::shared_ptr value_offsets, + std::shared_ptr value_sizes, std::shared_ptr values, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Construct ListViewArray from array of offsets, sizes, and child + /// value array + /// + /// Construct a ListViewArray using buffers from offsets and sizes arrays + /// that project views into the child values array. + /// + /// This function does the bare minimum of validation of the offsets/sizes and + /// input types. The offset and length of the offsets and sizes arrays must + /// match and that will be checked, but their contents will be assumed to be + /// well-formed. + /// + /// If a null_bitmap is not provided, the nulls will be inferred from the + /// offsets's null bitmap. But if a null_bitmap is provided, the offsets array + /// can't have nulls. + /// + /// And when a null_bitmap is provided, neither the offsets or sizes array can be a + /// slice (i.e. an array with offset() > 0). + /// + /// \param[in] offsets An array of int32 offsets into the values array. NULL values are + /// supported if the corresponding values in sizes is NULL or 0. + /// \param[in] sizes An array containing the int32 sizes of every view. NULL values are + /// taken to represent a NULL list-view in the array being created. + /// \param[in] values Array containing list values + /// \param[in] pool MemoryPool + /// \param[in] null_bitmap Optional validity bitmap + /// \param[in] null_count Optional null count in null_bitmap + static Result> FromArrays( + const Array& offsets, const Array& sizes, const Array& values, + MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + static Result> FromArrays( + std::shared_ptr type, const Array& offsets, const Array& sizes, + const Array& values, MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + /// \brief Build a ListViewArray from a ListArray + static Result> FromList(const ListArray& list_array, + MemoryPool* pool); + + /// \brief Return an Array that is a concatenation of the list-views in this array. + /// + /// Note that it's different from `values()` in that it takes into + /// consideration this array's offsets (which can be in any order) + /// and sizes. Nulls are skipped. + /// + /// This function invokes Concatenate() if list-views are non-contiguous. It + /// will try to minimize the number of array slices passed to Concatenate() by + /// maximizing the size of each slice (containing as many contiguous + /// list-views as possible). + Result> Flatten( + MemoryPool* memory_pool = default_memory_pool()) const; + + /// \brief Return list-view offsets as an Int32Array + /// + /// The returned array will not have a validity bitmap, so you cannot expect + /// to pass it to ListArray::FromArrays() and get back the same list array + /// if the original one has nulls. + std::shared_ptr offsets() const; + + /// \brief Return list-view sizes as an Int32Array + /// + /// The returned array will not have a validity bitmap, so you cannot expect + /// to pass it to ListViewArray::FromArrays() and get back the same list + /// array if the original one has nulls. + std::shared_ptr sizes() const; + + protected: + // This constructor defers SetData to a derived array class + ListViewArray() = default; + + void SetData(const std::shared_ptr& data); +}; + +/// \brief Concrete Array class for large list-view data (with 64-bit offsets +/// and sizes) +class ARROW_EXPORT LargeListViewArray : public BaseListViewArray { + public: + explicit LargeListViewArray(std::shared_ptr data); + + LargeListViewArray(std::shared_ptr type, int64_t length, + std::shared_ptr value_offsets, + std::shared_ptr value_sizes, std::shared_ptr values, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Construct LargeListViewArray from array of offsets, sizes, and child + /// value array + /// + /// Construct an LargeListViewArray using buffers from offsets and sizes arrays + /// that project views into the values array. + /// + /// This function does the bare minimum of validation of the offsets/sizes and + /// input types. The offset and length of the offsets and sizes arrays must + /// match and that will be checked, but their contents will be assumed to be + /// well-formed. + /// + /// If a null_bitmap is not provided, the nulls will be inferred from the offsets' or + /// sizes' null bitmap. Only one of these two is allowed to have a null bitmap. But if a + /// null_bitmap is provided, the offsets array and the sizes array can't have nulls. + /// + /// And when a null_bitmap is provided, neither the offsets or sizes array can be a + /// slice (i.e. an array with offset() > 0). + /// + /// \param[in] offsets An array of int64 offsets into the values array. NULL values are + /// supported if the corresponding values in sizes is NULL or 0. + /// \param[in] sizes An array containing the int64 sizes of every view. NULL values are + /// taken to represent a NULL list-view in the array being created. + /// \param[in] values Array containing list values + /// \param[in] pool MemoryPool + /// \param[in] null_bitmap Optional validity bitmap + /// \param[in] null_count Optional null count in null_bitmap + static Result> FromArrays( + const Array& offsets, const Array& sizes, const Array& values, + MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + static Result> FromArrays( + std::shared_ptr type, const Array& offsets, const Array& sizes, + const Array& values, MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + /// \brief Build a LargeListViewArray from a LargeListArray + static Result> FromList( + const LargeListArray& list_array, MemoryPool* pool); + + /// \brief Return an Array that is a concatenation of the large list-views in this + /// array. + /// + /// Note that it's different from `values()` in that it takes into + /// consideration this array's offsets (which can be in any order) + /// and sizes. Nulls are skipped. + Result> Flatten( + MemoryPool* memory_pool = default_memory_pool()) const; + + /// \brief Return list-view offsets as an Int64Array + /// + /// The returned array will not have a validity bitmap, so you cannot expect + /// to pass it to LargeListArray::FromArrays() and get back the same list array + /// if the original one has nulls. + std::shared_ptr offsets() const; + + /// \brief Return list-view sizes as an Int64Array + /// + /// The returned array will not have a validity bitmap, so you cannot expect + /// to pass it to LargeListViewArray::FromArrays() and get back the same list + /// array if the original one has nulls. + std::shared_ptr sizes() const; + + protected: + // This constructor defers SetData to a derived array class + LargeListViewArray() = default; + + void SetData(const std::shared_ptr& data); +}; + +// ---------------------------------------------------------------------- +// MapArray + +/// Concrete Array class for map data +/// +/// NB: "value" in this context refers to a pair of a key and the corresponding item +class ARROW_EXPORT MapArray : public ListArray { + public: + using TypeClass = MapType; + + explicit MapArray(const std::shared_ptr& data); + + MapArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& value_offsets, + const std::shared_ptr& keys, const std::shared_ptr& items, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + MapArray(const std::shared_ptr& type, int64_t length, BufferVector buffers, + const std::shared_ptr& keys, const std::shared_ptr& items, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + MapArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& value_offsets, + const std::shared_ptr& values, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Construct MapArray from array of offsets and child key, item arrays + /// + /// This function does the bare minimum of validation of the offsets and + /// input types, and will allocate a new offsets array if necessary (i.e. if + /// the offsets contain any nulls). If the offsets do not have nulls, they + /// are assumed to be well-formed + /// + /// \param[in] offsets Array containing n + 1 offsets encoding length and + /// size. Must be of int32 type + /// \param[in] keys Array containing key values + /// \param[in] items Array containing item values + /// \param[in] pool MemoryPool in case new offsets array needs to be + /// \param[in] null_bitmap Optional validity bitmap + /// allocated because of null values + static Result> FromArrays( + const std::shared_ptr& offsets, const std::shared_ptr& keys, + const std::shared_ptr& items, MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR); + + static Result> FromArrays( + std::shared_ptr type, const std::shared_ptr& offsets, + const std::shared_ptr& keys, const std::shared_ptr& items, + MemoryPool* pool = default_memory_pool(), + std::shared_ptr null_bitmap = NULLPTR); + + const MapType* map_type() const { return map_type_; } + + /// \brief Return array object containing all map keys + const std::shared_ptr& keys() const { return keys_; } + + /// \brief Return array object containing all mapped items + const std::shared_ptr& items() const { return items_; } + + /// Validate child data before constructing the actual MapArray. + static Status ValidateChildData( + const std::vector>& child_data); + + protected: + void SetData(const std::shared_ptr& data); + + static Result> FromArraysInternal( + std::shared_ptr type, const std::shared_ptr& offsets, + const std::shared_ptr& keys, const std::shared_ptr& items, + MemoryPool* pool, std::shared_ptr null_bitmap = NULLPTR); + + private: + const MapType* map_type_; + std::shared_ptr keys_, items_; +}; + +// ---------------------------------------------------------------------- +// FixedSizeListArray + +/// Concrete Array class for fixed size list data +class ARROW_EXPORT FixedSizeListArray : public Array { + public: + using TypeClass = FixedSizeListType; + using offset_type = TypeClass::offset_type; + + explicit FixedSizeListArray(const std::shared_ptr& data); + + FixedSizeListArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& values, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + const FixedSizeListType* list_type() const; + + /// \brief Return array object containing the list's values + const std::shared_ptr& values() const; + + const std::shared_ptr& value_type() const; + + // The following functions will not perform boundschecking + int64_t value_offset(int64_t i) const { + i += data_->offset; + return list_size_ * i; + } + /// \brief Return the fixed-size of the values + /// + /// No matter the value of the index parameter, the result is the same. + /// So even when the value at slot i is null, this function will return a + /// non-zero size. + /// + /// \pre IsValid(i) + int32_t value_length(int64_t i = 0) const { + ARROW_UNUSED(i); + return list_size_; + } + /// \pre IsValid(i) + std::shared_ptr value_slice(int64_t i) const { + return values_->Slice(value_offset(i), value_length(i)); + } + + /// \brief Return an Array that is a concatenation of the lists in this array. + /// + /// Note that it's different from `values()` in that it takes into + /// consideration null elements (they are skipped, thus copying may be needed). + Result> Flatten( + MemoryPool* memory_pool = default_memory_pool()) const; + + /// \brief Flatten all level recursively until reach a non-list type, and return + /// a non-list type Array. + /// + /// \see internal::FlattenLogicalListRecursively + Result> FlattenRecursively( + MemoryPool* memory_pool = default_memory_pool()) const { + return internal::FlattenLogicalListRecursively(*this, memory_pool); + } + + /// \brief Construct FixedSizeListArray from child value array and value_length + /// + /// \param[in] values Array containing list values + /// \param[in] list_size The fixed length of each list + /// \param[in] null_bitmap Optional validity bitmap + /// \param[in] null_count Optional null count in null_bitmap + /// \return Will have length equal to values.length() / list_size + static Result> FromArrays( + const std::shared_ptr& values, int32_t list_size, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + /// \brief Construct FixedSizeListArray from child value array and type + /// + /// \param[in] values Array containing list values + /// \param[in] type The fixed sized list type + /// \param[in] null_bitmap Optional validity bitmap + /// \param[in] null_count Optional null count in null_bitmap + /// \return Will have length equal to values.length() / type.list_size() + static Result> FromArrays( + const std::shared_ptr& values, std::shared_ptr type, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount); + + protected: + void SetData(const std::shared_ptr& data); + int32_t list_size_; + + private: + std::shared_ptr values_; +}; + +// ---------------------------------------------------------------------- +// Struct + +/// Concrete Array class for struct data +class ARROW_EXPORT StructArray : public Array { + public: + using TypeClass = StructType; + + ~StructArray() override; + + explicit StructArray(const std::shared_ptr& data); + + StructArray(const std::shared_ptr& type, int64_t length, + const std::vector>& children, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Return a StructArray from child arrays and field names. + /// + /// The length and data type are automatically inferred from the arguments. + /// There should be at least one child array. + static Result> Make( + const ArrayVector& children, const std::vector& field_names, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + /// \brief Return a StructArray from child arrays and fields. + /// + /// The length is automatically inferred from the arguments. + /// There should be at least one child array. This method does not + /// check that field types and child array types are consistent. + static Result> Make( + const ArrayVector& children, const FieldVector& fields, + std::shared_ptr null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + const StructType* struct_type() const; + + // Return a shared pointer in case the requestor desires to share ownership + // with this array. The returned array has its offset, length and null + // count adjusted. + std::shared_ptr field(int pos) const; + + const ArrayVector& fields() const; + + /// Returns null if name not found + std::shared_ptr GetFieldByName(const std::string& name) const; + + /// Indicate if field named `name` can be found unambiguously in the struct. + Status CanReferenceFieldByName(const std::string& name) const; + + /// Indicate if fields named `names` can be found unambiguously in the struct. + Status CanReferenceFieldsByNames(const std::vector& names) const; + + /// \brief Flatten this array as a vector of arrays, one for each field + /// + /// \param[in] pool The pool to allocate null bitmaps from, if necessary + Result Flatten(MemoryPool* pool = default_memory_pool()) const; + + /// \brief Get one of the child arrays, combining its null bitmap + /// with the parent struct array's bitmap. + /// + /// \param[in] index Which child array to get + /// \param[in] pool The pool to allocate null bitmaps from, if necessary + Result> GetFlattenedField( + int index, MemoryPool* pool = default_memory_pool()) const; + + private: + // For caching boxed child data + struct ARROW_NO_EXPORT Impl; + std::unique_ptr impl_; +}; + +// ---------------------------------------------------------------------- +// Union + +/// Base class for SparseUnionArray and DenseUnionArray +class ARROW_EXPORT UnionArray : public Array { + public: + using type_code_t = int8_t; + + ~UnionArray() override; + + /// Note that this buffer does not account for any slice offset + const std::shared_ptr& type_codes() const { return data_->buffers[1]; } + + const type_code_t* raw_type_codes() const { return raw_type_codes_; } + + /// The logical type code of the value at index. + type_code_t type_code(int64_t i) const { return raw_type_codes_[i]; } + + /// The physical child id containing value at index. + int child_id(int64_t i) const { return union_type_->child_ids()[raw_type_codes_[i]]; } + + const UnionType* union_type() const { return union_type_; } + + UnionMode::type mode() const { return union_type_->mode(); } + + /// \brief Return the given field as an individual array. + /// + /// For sparse unions, the returned array has its offset, length and null + /// count adjusted. + std::shared_ptr field(int pos) const; + + protected: + UnionArray(); + + void SetData(std::shared_ptr data); + + const type_code_t* raw_type_codes_; + const UnionType* union_type_; + + private: + // For caching boxed child data + struct ARROW_NO_EXPORT Impl; + std::unique_ptr impl_; +}; + +/// Concrete Array class for sparse union data +class ARROW_EXPORT SparseUnionArray : public UnionArray { + public: + using TypeClass = SparseUnionType; + + ~SparseUnionArray() override; + + explicit SparseUnionArray(std::shared_ptr data); + + SparseUnionArray(std::shared_ptr type, int64_t length, ArrayVector children, + std::shared_ptr type_ids, int64_t offset = 0); + + /// \brief Construct SparseUnionArray from type_ids and children + /// + /// This function does the bare minimum of validation of the input types. + /// + /// \param[in] type_ids An array of logical type ids for the union type + /// \param[in] children Vector of children Arrays containing the data for each type. + /// \param[in] type_codes Vector of type codes. + static Result> Make(const Array& type_ids, ArrayVector children, + std::vector type_codes) { + return Make(std::move(type_ids), std::move(children), std::vector{}, + std::move(type_codes)); + } + + /// \brief Construct SparseUnionArray with custom field names from type_ids and children + /// + /// This function does the bare minimum of validation of the input types. + /// + /// \param[in] type_ids An array of logical type ids for the union type + /// \param[in] children Vector of children Arrays containing the data for each type. + /// \param[in] field_names Vector of strings containing the name of each field. + /// \param[in] type_codes Vector of type codes. + static Result> Make(const Array& type_ids, ArrayVector children, + std::vector field_names = {}, + std::vector type_codes = {}); + + const SparseUnionType* union_type() const { + return internal::checked_cast(union_type_); + } + + /// \brief Get one of the child arrays, adjusting its null bitmap + /// where the union array type code does not match. + /// + /// \param[in] index Which child array to get (i.e. the physical index, not the type + /// code) \param[in] pool The pool to allocate null bitmaps from, if necessary + Result> GetFlattenedField( + int index, MemoryPool* pool = default_memory_pool()) const; + + protected: + void SetData(std::shared_ptr data); +}; + +/// \brief Concrete Array class for dense union data +/// +/// Note that union types do not have a validity bitmap +class ARROW_EXPORT DenseUnionArray : public UnionArray { + public: + using TypeClass = DenseUnionType; + + ~DenseUnionArray() override; + + explicit DenseUnionArray(const std::shared_ptr& data); + + DenseUnionArray(std::shared_ptr type, int64_t length, ArrayVector children, + std::shared_ptr type_ids, + std::shared_ptr value_offsets = NULLPTR, int64_t offset = 0); + + /// \brief Construct DenseUnionArray from type_ids, value_offsets, and children + /// + /// This function does the bare minimum of validation of the offsets and + /// input types. + /// + /// \param[in] type_ids An array of logical type ids for the union type + /// \param[in] value_offsets An array of signed int32 values indicating the + /// relative offset into the respective child array for the type in a given slot. + /// The respective offsets for each child value array must be in order / increasing. + /// \param[in] children Vector of children Arrays containing the data for each type. + /// \param[in] type_codes Vector of type codes. + static Result> Make(const Array& type_ids, + const Array& value_offsets, + ArrayVector children, + std::vector type_codes) { + return Make(type_ids, value_offsets, std::move(children), std::vector{}, + std::move(type_codes)); + } + + /// \brief Construct DenseUnionArray with custom field names from type_ids, + /// value_offsets, and children + /// + /// This function does the bare minimum of validation of the offsets and + /// input types. + /// + /// \param[in] type_ids An array of logical type ids for the union type + /// \param[in] value_offsets An array of signed int32 values indicating the + /// relative offset into the respective child array for the type in a given slot. + /// The respective offsets for each child value array must be in order / increasing. + /// \param[in] children Vector of children Arrays containing the data for each type. + /// \param[in] field_names Vector of strings containing the name of each field. + /// \param[in] type_codes Vector of type codes. + static Result> Make(const Array& type_ids, + const Array& value_offsets, + ArrayVector children, + std::vector field_names = {}, + std::vector type_codes = {}); + + const DenseUnionType* union_type() const { + return internal::checked_cast(union_type_); + } + + /// Note that this buffer does not account for any slice offset + const std::shared_ptr& value_offsets() const { return data_->buffers[2]; } + + int32_t value_offset(int64_t i) const { return raw_value_offsets_[i]; } + + const int32_t* raw_value_offsets() const { return raw_value_offsets_; } + + protected: + const int32_t* raw_value_offsets_; + + void SetData(const std::shared_ptr& data); +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_primitive.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_primitive.h new file mode 100644 index 0000000000000000000000000000000000000000..cebf47ad93d8aa719328007f3c4fa6d960855027 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_primitive.h @@ -0,0 +1,220 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Array accessor types for primitive/C-type-based arrays, such as numbers, +// boolean, and temporal types. + +#pragma once + +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/data.h" +#include "arrow/stl_iterator.h" +#include "arrow/type.h" +#include "arrow/type_fwd.h" // IWYU pragma: export +#include "arrow/type_traits.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// Concrete Array class for boolean data +class ARROW_EXPORT BooleanArray : public PrimitiveArray { + public: + using TypeClass = BooleanType; + using IteratorType = stl::ArrayIterator; + + explicit BooleanArray(const std::shared_ptr& data); + + BooleanArray(int64_t length, const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + bool Value(int64_t i) const { + return bit_util::GetBit(reinterpret_cast(raw_values_), + i + data_->offset); + } + + bool GetView(int64_t i) const { return Value(i); } + + std::optional operator[](int64_t i) const { return *IteratorType(*this, i); } + + /// \brief Return the number of false (0) values among the valid + /// values. Result is not cached. + int64_t false_count() const; + + /// \brief Return the number of true (1) values among the valid + /// values. Result is not cached. + int64_t true_count() const; + + IteratorType begin() const { return IteratorType(*this); } + + IteratorType end() const { return IteratorType(*this, length()); } + + protected: + using PrimitiveArray::PrimitiveArray; +}; + +/// \addtogroup numeric-arrays +/// +/// @{ + +/// \brief Concrete Array class for numeric data with a corresponding C type +/// +/// This class is templated on the corresponding DataType subclass for the +/// given data, for example NumericArray or NumericArray. +/// +/// Note that convenience aliases are available for all accepted types +/// (for example Int8Array for NumericArray). +template +class NumericArray : public PrimitiveArray { + public: + using TypeClass = TYPE; + using value_type = typename TypeClass::c_type; + using IteratorType = stl::ArrayIterator>; + + explicit NumericArray(const std::shared_ptr& data) { + NumericArray::SetData(data); + } + + // Only enable this constructor without a type argument for types without additional + // metadata + template + NumericArray(enable_if_parameter_free length, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0) { + NumericArray::SetData(ArrayData::Make(TypeTraits::type_singleton(), length, + {null_bitmap, data}, null_count, offset)); + } + + NumericArray(std::shared_ptr type, int64_t length, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0) { + NumericArray::SetData(ArrayData::Make(std::move(type), length, {null_bitmap, data}, + null_count, offset)); + } + + const value_type* raw_values() const { return values_; } + + value_type Value(int64_t i) const { return values_[i]; } + + // For API compatibility with BinaryArray etc. + value_type GetView(int64_t i) const { return values_[i]; } + + std::optional operator[](int64_t i) const { + return *IteratorType(*this, i); + } + + IteratorType begin() const { return IteratorType(*this); } + + IteratorType end() const { return IteratorType(*this, length()); } + + protected: + NumericArray() : values_(NULLPTR) {} + + void SetData(const std::shared_ptr& data) { + this->PrimitiveArray::SetData(data); + values_ = raw_values_ + ? (reinterpret_cast(raw_values_) + data_->offset) + : NULLPTR; + } + + const value_type* values_; +}; + +/// DayTimeArray +/// --------------------- +/// \brief Array of Day and Millisecond values. +class ARROW_EXPORT DayTimeIntervalArray : public PrimitiveArray { + public: + using TypeClass = DayTimeIntervalType; + using IteratorType = stl::ArrayIterator; + + explicit DayTimeIntervalArray(const std::shared_ptr& data); + + DayTimeIntervalArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + DayTimeIntervalArray(int64_t length, const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + TypeClass::DayMilliseconds GetValue(int64_t i) const; + TypeClass::DayMilliseconds Value(int64_t i) const { return GetValue(i); } + + // For compatibility with Take kernel. + TypeClass::DayMilliseconds GetView(int64_t i) const { return GetValue(i); } + + IteratorType begin() const { return IteratorType(*this); } + + IteratorType end() const { return IteratorType(*this, length()); } + + std::optional operator[](int64_t i) const { + return *IteratorType(*this, i); + } + + int32_t byte_width() const { return sizeof(TypeClass::DayMilliseconds); } + + const uint8_t* raw_values() const { return raw_values_ + data_->offset * byte_width(); } +}; + +/// \brief Array of Month, Day and nanosecond values. +class ARROW_EXPORT MonthDayNanoIntervalArray : public PrimitiveArray { + public: + using TypeClass = MonthDayNanoIntervalType; + using IteratorType = stl::ArrayIterator; + + explicit MonthDayNanoIntervalArray(const std::shared_ptr& data); + + MonthDayNanoIntervalArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + MonthDayNanoIntervalArray(int64_t length, const std::shared_ptr& data, + const std::shared_ptr& null_bitmap = NULLPTR, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + TypeClass::MonthDayNanos GetValue(int64_t i) const; + TypeClass::MonthDayNanos Value(int64_t i) const { return GetValue(i); } + + // For compatibility with Take kernel. + TypeClass::MonthDayNanos GetView(int64_t i) const { return GetValue(i); } + + IteratorType begin() const { return IteratorType(*this); } + + IteratorType end() const { return IteratorType(*this, length()); } + + std::optional operator[](int64_t i) const { + return *IteratorType(*this, i); + } + + int32_t byte_width() const { return sizeof(TypeClass::MonthDayNanos); } + + const uint8_t* raw_values() const { return raw_values_ + data_->offset * byte_width(); } +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_run_end.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_run_end.h new file mode 100644 index 0000000000000000000000000000000000000000..b46b0855ab36776eec4e22cef1a35112e2d18fa8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/array_run_end.h @@ -0,0 +1,133 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Array accessor classes run-end encoded arrays + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/data.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_fwd.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup run-end-encoded-arrays +/// +/// @{ + +// ---------------------------------------------------------------------- +// RunEndEncoded + +/// \brief Array type for run-end encoded data +class ARROW_EXPORT RunEndEncodedArray : public Array { + private: + std::shared_ptr run_ends_array_; + std::shared_ptr values_array_; + + public: + using TypeClass = RunEndEncodedType; + + explicit RunEndEncodedArray(const std::shared_ptr& data); + + /// \brief Construct a RunEndEncodedArray from all parameters + /// + /// The length and offset parameters refer to the dimensions of the logical + /// array which is the array we would get after expanding all the runs into + /// repeated values. As such, length can be much greater than the length of + /// the child run_ends and values arrays. + RunEndEncodedArray(const std::shared_ptr& type, int64_t length, + const std::shared_ptr& run_ends, + const std::shared_ptr& values, int64_t offset = 0); + + /// \brief Construct a RunEndEncodedArray from all parameters + /// + /// The length and offset parameters refer to the dimensions of the logical + /// array which is the array we would get after expanding all the runs into + /// repeated values. As such, length can be much greater than the length of + /// the child run_ends and values arrays. + static Result> Make( + const std::shared_ptr& type, int64_t logical_length, + const std::shared_ptr& run_ends, const std::shared_ptr& values, + int64_t logical_offset = 0); + + /// \brief Construct a RunEndEncodedArray from values and run ends arrays + /// + /// The data type is automatically inferred from the arguments. + /// The run_ends and values arrays must have the same length. + static Result> Make( + int64_t logical_length, const std::shared_ptr& run_ends, + const std::shared_ptr& values, int64_t logical_offset = 0); + + protected: + void SetData(const std::shared_ptr& data); + + public: + /// \brief Returns an array holding the logical indexes of each run-end + /// + /// The physical offset to the array is applied. + const std::shared_ptr& run_ends() const { return run_ends_array_; } + + /// \brief Returns an array holding the values of each run + /// + /// The physical offset to the array is applied. + const std::shared_ptr& values() const { return values_array_; } + + /// \brief Returns an array holding the logical indexes of each run end + /// + /// If a non-zero logical offset is set, this function allocates a new + /// array and rewrites all the run end values to be relative to the logical + /// offset and cuts the end of the array to the logical length. + Result> LogicalRunEnds(MemoryPool* pool) const; + + /// \brief Returns an array holding the values of each run + /// + /// If a non-zero logical offset is set, this function allocates a new + /// array containing only the values within the logical range. + std::shared_ptr LogicalValues() const; + + /// \brief Find the physical offset of this REE array + /// + /// This function uses binary-search, so it has a O(log N) cost. + int64_t FindPhysicalOffset() const; + + /// \brief Find the physical length of this REE array + /// + /// The physical length of an REE is the number of physical values (and + /// run-ends) necessary to represent the logical range of values from offset + /// to length. + /// + /// Avoid calling this function if the physical length can be established in + /// some other way (e.g. when iterating over the runs sequentially until the + /// end). This function uses binary-search, so it has a O(log N) cost. + int64_t FindPhysicalLength() const; +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_adaptive.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_adaptive.h new file mode 100644 index 0000000000000000000000000000000000000000..0cea571be3e3244741f3df15f87c8958eedddf76 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_adaptive.h @@ -0,0 +1,215 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/array/builder_base.h" +#include "arrow/buffer.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup numeric-builders +/// +/// @{ + +namespace internal { + +class ARROW_EXPORT AdaptiveIntBuilderBase : public ArrayBuilder { + public: + AdaptiveIntBuilderBase(uint8_t start_int_size, MemoryPool* pool, + int64_t alignment = kDefaultBufferAlignment); + + explicit AdaptiveIntBuilderBase(MemoryPool* pool, + int64_t alignment = kDefaultBufferAlignment) + : AdaptiveIntBuilderBase(sizeof(uint8_t), pool, alignment) {} + + /// \brief Append multiple nulls + /// \param[in] length the number of nulls to append + Status AppendNulls(int64_t length) final { + ARROW_RETURN_NOT_OK(CommitPendingData()); + if (ARROW_PREDICT_TRUE(length > 0)) { + ARROW_RETURN_NOT_OK(Reserve(length)); + memset(data_->mutable_data() + length_ * int_size_, 0, int_size_ * length); + UnsafeSetNull(length); + } + return Status::OK(); + } + + Status AppendNull() final { + pending_data_[pending_pos_] = 0; + pending_valid_[pending_pos_] = 0; + pending_has_nulls_ = true; + ++pending_pos_; + ++length_; + ++null_count_; + + if (ARROW_PREDICT_FALSE(pending_pos_ >= pending_size_)) { + return CommitPendingData(); + } + return Status::OK(); + } + + Status AppendEmptyValues(int64_t length) final { + ARROW_RETURN_NOT_OK(CommitPendingData()); + if (ARROW_PREDICT_TRUE(length > 0)) { + ARROW_RETURN_NOT_OK(Reserve(length)); + memset(data_->mutable_data() + length_ * int_size_, 0, int_size_ * length); + UnsafeSetNotNull(length); + } + return Status::OK(); + } + + Status AppendEmptyValue() final { + pending_data_[pending_pos_] = 0; + pending_valid_[pending_pos_] = 1; + ++pending_pos_; + ++length_; + + if (ARROW_PREDICT_FALSE(pending_pos_ >= pending_size_)) { + return CommitPendingData(); + } + return Status::OK(); + } + + void Reset() override; + Status Resize(int64_t capacity) override; + + protected: + Status AppendInternal(const uint64_t val) { + pending_data_[pending_pos_] = val; + pending_valid_[pending_pos_] = 1; + ++pending_pos_; + ++length_; + + if (ARROW_PREDICT_FALSE(pending_pos_ >= pending_size_)) { + return CommitPendingData(); + } + return Status::OK(); + } + + virtual Status CommitPendingData() = 0; + + template + typename std::enable_if= sizeof(new_type), Status>::type + ExpandIntSizeInternal(); + template + typename std::enable_if<(sizeof(old_type) < sizeof(new_type)), Status>::type + ExpandIntSizeInternal(); + + std::shared_ptr data_; + uint8_t* raw_data_ = NULLPTR; + + const uint8_t start_int_size_; + uint8_t int_size_; + + static constexpr int32_t pending_size_ = 1024; + uint8_t pending_valid_[pending_size_]; + uint64_t pending_data_[pending_size_]; + int32_t pending_pos_ = 0; + bool pending_has_nulls_ = false; +}; + +} // namespace internal + +class ARROW_EXPORT AdaptiveUIntBuilder : public internal::AdaptiveIntBuilderBase { + public: + explicit AdaptiveUIntBuilder(uint8_t start_int_size, + MemoryPool* pool = default_memory_pool()); + + explicit AdaptiveUIntBuilder(MemoryPool* pool = default_memory_pool()) + : AdaptiveUIntBuilder(sizeof(uint8_t), pool) {} + + using internal::AdaptiveIntBuilderBase::Reset; + + /// Scalar append + Status Append(const uint64_t val) { return AppendInternal(val); } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous C array of values + /// \param[in] length the number of values to append + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const uint64_t* values, int64_t length, + const uint8_t* valid_bytes = NULLPTR); + + Status FinishInternal(std::shared_ptr* out) override; + + std::shared_ptr type() const override; + + protected: + Status CommitPendingData() override; + Status ExpandIntSize(uint8_t new_int_size); + + Status AppendValuesInternal(const uint64_t* values, int64_t length, + const uint8_t* valid_bytes); + + template + Status ExpandIntSizeN(); +}; + +class ARROW_EXPORT AdaptiveIntBuilder : public internal::AdaptiveIntBuilderBase { + public: + explicit AdaptiveIntBuilder(uint8_t start_int_size, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + explicit AdaptiveIntBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : AdaptiveIntBuilder(sizeof(uint8_t), pool, alignment) {} + + using internal::AdaptiveIntBuilderBase::Reset; + + /// Scalar append + Status Append(const int64_t val) { return AppendInternal(static_cast(val)); } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous C array of values + /// \param[in] length the number of values to append + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const int64_t* values, int64_t length, + const uint8_t* valid_bytes = NULLPTR); + + Status FinishInternal(std::shared_ptr* out) override; + + std::shared_ptr type() const override; + + protected: + Status CommitPendingData() override; + Status ExpandIntSize(uint8_t new_int_size); + + Status AppendValuesInternal(const int64_t* values, int64_t length, + const uint8_t* valid_bytes); + + template + Status ExpandIntSizeN(); +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_base.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_base.h new file mode 100644 index 0000000000000000000000000000000000000000..ecd2136f5d20ba126bd359977ea17f76c4fe23ed --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_base.h @@ -0,0 +1,371 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include // IWYU pragma: keep +#include +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/array_primitive.h" +#include "arrow/buffer.h" +#include "arrow/buffer_builder.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +namespace internal { + +template +class ArrayBuilderExtraOps { + public: + /// \brief Append a value from an optional or null if it has no value. + Status AppendOrNull(const std::optional& value) { + auto* self = static_cast(this); + return value.has_value() ? self->Append(*value) : self->AppendNull(); + } + + /// \brief Append a value from an optional or null if it has no value. + /// + /// Unsafe methods don't check existing size. + void UnsafeAppendOrNull(const std::optional& value) { + auto* self = static_cast(this); + return value.has_value() ? self->UnsafeAppend(*value) : self->UnsafeAppendNull(); + } +}; + +} // namespace internal + +/// \defgroup numeric-builders Concrete builder subclasses for numeric types +/// @{ +/// @} + +/// \defgroup temporal-builders Concrete builder subclasses for temporal types +/// @{ +/// @} + +/// \defgroup binary-builders Concrete builder subclasses for binary types +/// @{ +/// @} + +/// \defgroup nested-builders Concrete builder subclasses for nested types +/// @{ +/// @} + +/// \defgroup dictionary-builders Concrete builder subclasses for dictionary types +/// @{ +/// @} + +/// \defgroup run-end-encoded-builders Concrete builder subclasses for run-end encoded +/// arrays +/// @{ +/// @} + +constexpr int64_t kMinBuilderCapacity = 1 << 5; +constexpr int64_t kListMaximumElements = std::numeric_limits::max() - 1; + +/// Base class for all data array builders. +/// +/// This class provides a facilities for incrementally building the null bitmap +/// (see Append methods) and as a side effect the current number of slots and +/// the null count. +/// +/// \note Users are expected to use builders as one of the concrete types below. +/// For example, ArrayBuilder* pointing to BinaryBuilder should be downcast before use. +class ARROW_EXPORT ArrayBuilder { + public: + explicit ArrayBuilder(MemoryPool* pool, int64_t alignment = kDefaultBufferAlignment) + : pool_(pool), alignment_(alignment), null_bitmap_builder_(pool, alignment) {} + + ARROW_DEFAULT_MOVE_AND_ASSIGN(ArrayBuilder); + + virtual ~ArrayBuilder() = default; + + /// For nested types. Since the objects are owned by this class instance, we + /// skip shared pointers and just return a raw pointer + ArrayBuilder* child(int i) { return children_[i].get(); } + + const std::shared_ptr& child_builder(int i) const { return children_[i]; } + + int num_children() const { return static_cast(children_.size()); } + + virtual int64_t length() const { return length_; } + int64_t null_count() const { return null_count_; } + int64_t capacity() const { return capacity_; } + + /// \brief Ensure that enough memory has been allocated to fit the indicated + /// number of total elements in the builder, including any that have already + /// been appended. Does not account for reallocations that may be due to + /// variable size data, like binary values. To make space for incremental + /// appends, use Reserve instead. + /// + /// \param[in] capacity the minimum number of total array values to + /// accommodate. Must be greater than the current capacity. + /// \return Status + virtual Status Resize(int64_t capacity); + + /// \brief Ensure that there is enough space allocated to append the indicated + /// number of elements without any further reallocation. Overallocation is + /// used in order to minimize the impact of incremental Reserve() calls. + /// Note that additional_capacity is relative to the current number of elements + /// rather than to the current capacity, so calls to Reserve() which are not + /// interspersed with addition of new elements may not increase the capacity. + /// + /// \param[in] additional_capacity the number of additional array values + /// \return Status + Status Reserve(int64_t additional_capacity) { + auto current_capacity = capacity(); + auto min_capacity = length() + additional_capacity; + if (min_capacity <= current_capacity) return Status::OK(); + + // leave growth factor up to BufferBuilder + auto new_capacity = BufferBuilder::GrowByFactor(current_capacity, min_capacity); + return Resize(new_capacity); + } + + /// Reset the builder. + virtual void Reset(); + + /// \brief Append a null value to builder + virtual Status AppendNull() = 0; + /// \brief Append a number of null values to builder + virtual Status AppendNulls(int64_t length) = 0; + + /// \brief Append a non-null value to builder + /// + /// The appended value is an implementation detail, but the corresponding + /// memory slot is guaranteed to be initialized. + /// This method is useful when appending a null value to a parent nested type. + virtual Status AppendEmptyValue() = 0; + + /// \brief Append a number of non-null values to builder + /// + /// The appended values are an implementation detail, but the corresponding + /// memory slot is guaranteed to be initialized. + /// This method is useful when appending null values to a parent nested type. + virtual Status AppendEmptyValues(int64_t length) = 0; + + /// \brief Append a value from a scalar + Status AppendScalar(const Scalar& scalar) { return AppendScalar(scalar, 1); } + virtual Status AppendScalar(const Scalar& scalar, int64_t n_repeats); + virtual Status AppendScalars(const ScalarVector& scalars); + + /// \brief Append a range of values from an array. + /// + /// The given array must be the same type as the builder. + virtual Status AppendArraySlice(const ArraySpan& ARROW_ARG_UNUSED(array), + int64_t ARROW_ARG_UNUSED(offset), + int64_t ARROW_ARG_UNUSED(length)) { + return Status::NotImplemented("AppendArraySlice for builder for ", *type()); + } + + /// \brief Return result of builder as an internal generic ArrayData + /// object. Resets builder except for dictionary builder + /// + /// \param[out] out the finalized ArrayData object + /// \return Status + virtual Status FinishInternal(std::shared_ptr* out) = 0; + + /// \brief Return result of builder as an Array object. + /// + /// The builder is reset except for DictionaryBuilder. + /// + /// \param[out] out the finalized Array object + /// \return Status + Status Finish(std::shared_ptr* out); + + /// \brief Return result of builder as an Array object. + /// + /// The builder is reset except for DictionaryBuilder. + /// + /// \return The finalized Array object + Result> Finish(); + + /// \brief Return the type of the built Array + virtual std::shared_ptr type() const = 0; + + protected: + /// Append to null bitmap + Status AppendToBitmap(bool is_valid); + + /// Vector append. Treat each zero byte as a null. If valid_bytes is null + /// assume all of length bits are valid. + Status AppendToBitmap(const uint8_t* valid_bytes, int64_t length); + + /// Uniform append. Append N times the same validity bit. + Status AppendToBitmap(int64_t num_bits, bool value); + + /// Set the next length bits to not null (i.e. valid). + Status SetNotNull(int64_t length); + + // Unsafe operations (don't check capacity/don't resize) + + void UnsafeAppendNull() { UnsafeAppendToBitmap(false); } + + // Append to null bitmap, update the length + void UnsafeAppendToBitmap(bool is_valid) { + null_bitmap_builder_.UnsafeAppend(is_valid); + ++length_; + if (!is_valid) ++null_count_; + } + + // Vector append. Treat each zero byte as a nullzero. If valid_bytes is null + // assume all of length bits are valid. + void UnsafeAppendToBitmap(const uint8_t* valid_bytes, int64_t length) { + if (valid_bytes == NULLPTR) { + return UnsafeSetNotNull(length); + } + null_bitmap_builder_.UnsafeAppend(valid_bytes, length); + length_ += length; + null_count_ = null_bitmap_builder_.false_count(); + } + + // Vector append. Copy from a given bitmap. If bitmap is null assume + // all of length bits are valid. + void UnsafeAppendToBitmap(const uint8_t* bitmap, int64_t offset, int64_t length) { + if (bitmap == NULLPTR) { + return UnsafeSetNotNull(length); + } + null_bitmap_builder_.UnsafeAppend(bitmap, offset, length); + length_ += length; + null_count_ = null_bitmap_builder_.false_count(); + } + + // Append the same validity value a given number of times. + void UnsafeAppendToBitmap(const int64_t num_bits, bool value) { + if (value) { + UnsafeSetNotNull(num_bits); + } else { + UnsafeSetNull(num_bits); + } + } + + void UnsafeAppendToBitmap(const std::vector& is_valid); + + // Set the next validity bits to not null (i.e. valid). + void UnsafeSetNotNull(int64_t length); + + // Set the next validity bits to null (i.e. invalid). + void UnsafeSetNull(int64_t length); + + static Status TrimBuffer(const int64_t bytes_filled, ResizableBuffer* buffer); + + /// \brief Finish to an array of the specified ArrayType + template + Status FinishTyped(std::shared_ptr* out) { + std::shared_ptr out_untyped; + ARROW_RETURN_NOT_OK(Finish(&out_untyped)); + *out = std::static_pointer_cast(std::move(out_untyped)); + return Status::OK(); + } + + // Check the requested capacity for validity + Status CheckCapacity(int64_t new_capacity) { + if (ARROW_PREDICT_FALSE(new_capacity < 0)) { + return Status::Invalid( + "Resize capacity must be positive (requested: ", new_capacity, ")"); + } + + if (ARROW_PREDICT_FALSE(new_capacity < length_)) { + return Status::Invalid("Resize cannot downsize (requested: ", new_capacity, + ", current length: ", length_, ")"); + } + + return Status::OK(); + } + + // Check for array type + Status CheckArrayType(const std::shared_ptr& expected_type, + const Array& array, const char* message); + Status CheckArrayType(Type::type expected_type, const Array& array, + const char* message); + + MemoryPool* pool_; + int64_t alignment_; + + TypedBufferBuilder null_bitmap_builder_; + int64_t null_count_ = 0; + + // Array length, so far. Also, the index of the next element to be added + int64_t length_ = 0; + int64_t capacity_ = 0; + + // Child value array builders. These are owned by this class + std::vector> children_; + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(ArrayBuilder); +}; + +/// \brief Construct an empty ArrayBuilder corresponding to the data +/// type +/// \param[in] pool the MemoryPool to use for allocations +/// \param[in] type the data type to create the builder for +/// \param[out] out the created ArrayBuilder +ARROW_EXPORT +Status MakeBuilder(MemoryPool* pool, const std::shared_ptr& type, + std::unique_ptr* out); + +inline Result> MakeBuilder( + const std::shared_ptr& type, MemoryPool* pool = default_memory_pool()) { + std::unique_ptr out; + ARROW_RETURN_NOT_OK(MakeBuilder(pool, type, &out)); + return out; +} + +/// \brief Construct an empty ArrayBuilder corresponding to the data +/// type, where any top-level or nested dictionary builders return the +/// exact index type specified by the type. +ARROW_EXPORT +Status MakeBuilderExactIndex(MemoryPool* pool, const std::shared_ptr& type, + std::unique_ptr* out); + +inline Result> MakeBuilderExactIndex( + const std::shared_ptr& type, MemoryPool* pool = default_memory_pool()) { + std::unique_ptr out; + ARROW_RETURN_NOT_OK(MakeBuilderExactIndex(pool, type, &out)); + return out; +} + +/// \brief Construct an empty DictionaryBuilder initialized optionally +/// with a preexisting dictionary +/// \param[in] pool the MemoryPool to use for allocations +/// \param[in] type the dictionary type to create the builder for +/// \param[in] dictionary the initial dictionary, if any. May be nullptr +/// \param[out] out the created ArrayBuilder +ARROW_EXPORT +Status MakeDictionaryBuilder(MemoryPool* pool, const std::shared_ptr& type, + const std::shared_ptr& dictionary, + std::unique_ptr* out); + +inline Result> MakeDictionaryBuilder( + const std::shared_ptr& type, const std::shared_ptr& dictionary, + MemoryPool* pool = default_memory_pool()) { + std::unique_ptr out; + ARROW_RETURN_NOT_OK(MakeDictionaryBuilder(pool, type, dictionary, &out)); + return out; +} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_binary.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_binary.h new file mode 100644 index 0000000000000000000000000000000000000000..d0e761ae9684132240f21ee335a996bdda081a63 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_binary.h @@ -0,0 +1,993 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/array_binary.h" +#include "arrow/array/builder_base.h" +#include "arrow/array/data.h" +#include "arrow/buffer.h" +#include "arrow/buffer_builder.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/binary_view_util.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup binary-builders +/// +/// @{ + +// ---------------------------------------------------------------------- +// Binary and String + +template +class BaseBinaryBuilder + : public ArrayBuilder, + public internal::ArrayBuilderExtraOps, std::string_view> { + public: + using TypeClass = TYPE; + using offset_type = typename TypeClass::offset_type; + + explicit BaseBinaryBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + offsets_builder_(pool, alignment), + value_data_builder_(pool, alignment) {} + + BaseBinaryBuilder(const std::shared_ptr& type, MemoryPool* pool) + : BaseBinaryBuilder(pool) {} + + Status Append(const uint8_t* value, offset_type length) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendNextOffset(); + // Safety check for UBSAN. + if (ARROW_PREDICT_TRUE(length > 0)) { + ARROW_RETURN_NOT_OK(ValidateOverflow(length)); + ARROW_RETURN_NOT_OK(value_data_builder_.Append(value, length)); + } + + UnsafeAppendToBitmap(true); + return Status::OK(); + } + + Status Append(const char* value, offset_type length) { + return Append(reinterpret_cast(value), length); + } + + Status Append(std::string_view value) { + return Append(value.data(), static_cast(value.size())); + } + + /// Extend the last appended value by appending more data at the end + /// + /// Unlike Append, this does not create a new offset. + Status ExtendCurrent(const uint8_t* value, offset_type length) { + // Safety check for UBSAN. + if (ARROW_PREDICT_TRUE(length > 0)) { + ARROW_RETURN_NOT_OK(ValidateOverflow(length)); + ARROW_RETURN_NOT_OK(value_data_builder_.Append(value, length)); + } + return Status::OK(); + } + + Status ExtendCurrent(std::string_view value) { + return ExtendCurrent(reinterpret_cast(value.data()), + static_cast(value.size())); + } + + Status AppendNulls(int64_t length) final { + const int64_t num_bytes = value_data_builder_.length(); + ARROW_RETURN_NOT_OK(Reserve(length)); + for (int64_t i = 0; i < length; ++i) { + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + } + UnsafeAppendToBitmap(length, false); + return Status::OK(); + } + + Status AppendNull() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendNextOffset(); + UnsafeAppendToBitmap(false); + return Status::OK(); + } + + Status AppendEmptyValue() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendNextOffset(); + UnsafeAppendToBitmap(true); + return Status::OK(); + } + + Status AppendEmptyValues(int64_t length) final { + const int64_t num_bytes = value_data_builder_.length(); + ARROW_RETURN_NOT_OK(Reserve(length)); + for (int64_t i = 0; i < length; ++i) { + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + } + UnsafeAppendToBitmap(length, true); + return Status::OK(); + } + + /// \brief Append without checking capacity + /// + /// Offsets and data should have been presized using Reserve() and + /// ReserveData(), respectively. + void UnsafeAppend(const uint8_t* value, offset_type length) { + UnsafeAppendNextOffset(); + value_data_builder_.UnsafeAppend(value, length); + UnsafeAppendToBitmap(true); + } + + void UnsafeAppend(const char* value, offset_type length) { + UnsafeAppend(reinterpret_cast(value), length); + } + + void UnsafeAppend(const std::string& value) { + UnsafeAppend(value.c_str(), static_cast(value.size())); + } + + void UnsafeAppend(std::string_view value) { + UnsafeAppend(value.data(), static_cast(value.size())); + } + + /// Like ExtendCurrent, but do not check capacity + void UnsafeExtendCurrent(const uint8_t* value, offset_type length) { + value_data_builder_.UnsafeAppend(value, length); + } + + void UnsafeExtendCurrent(std::string_view value) { + UnsafeExtendCurrent(reinterpret_cast(value.data()), + static_cast(value.size())); + } + + void UnsafeAppendNull() { + const int64_t num_bytes = value_data_builder_.length(); + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + UnsafeAppendToBitmap(false); + } + + void UnsafeAppendEmptyValue() { + const int64_t num_bytes = value_data_builder_.length(); + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + UnsafeAppendToBitmap(true); + } + + /// \brief Append a sequence of strings in one shot. + /// + /// \param[in] values a vector of strings + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const std::vector& values, + const uint8_t* valid_bytes = NULLPTR) { + std::size_t total_length = std::accumulate( + values.begin(), values.end(), 0ULL, + [](uint64_t sum, const std::string& str) { return sum + str.size(); }); + ARROW_RETURN_NOT_OK(Reserve(values.size())); + ARROW_RETURN_NOT_OK(ReserveData(total_length)); + + if (valid_bytes != NULLPTR) { + for (std::size_t i = 0; i < values.size(); ++i) { + UnsafeAppendNextOffset(); + if (valid_bytes[i]) { + value_data_builder_.UnsafeAppend( + reinterpret_cast(values[i].data()), values[i].size()); + } + } + } else { + for (const auto& value : values) { + UnsafeAppendNextOffset(); + value_data_builder_.UnsafeAppend(reinterpret_cast(value.data()), + value.size()); + } + } + + UnsafeAppendToBitmap(valid_bytes, values.size()); + return Status::OK(); + } + + /// \brief Append a sequence of nul-terminated strings in one shot. + /// If one of the values is NULL, it is processed as a null + /// value even if the corresponding valid_bytes entry is 1. + /// + /// \param[in] values a contiguous C array of nul-terminated char * + /// \param[in] length the number of values to append + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const char** values, int64_t length, + const uint8_t* valid_bytes = NULLPTR) { + std::size_t total_length = 0; + std::vector value_lengths(length); + bool have_null_value = false; + for (int64_t i = 0; i < length; ++i) { + if (values[i] != NULLPTR) { + auto value_length = strlen(values[i]); + value_lengths[i] = value_length; + total_length += value_length; + } else { + have_null_value = true; + } + } + ARROW_RETURN_NOT_OK(Reserve(length)); + ARROW_RETURN_NOT_OK(ReserveData(total_length)); + + if (valid_bytes) { + int64_t valid_bytes_offset = 0; + for (int64_t i = 0; i < length; ++i) { + UnsafeAppendNextOffset(); + if (valid_bytes[i]) { + if (values[i]) { + value_data_builder_.UnsafeAppend(reinterpret_cast(values[i]), + value_lengths[i]); + } else { + UnsafeAppendToBitmap(valid_bytes + valid_bytes_offset, + i - valid_bytes_offset); + UnsafeAppendToBitmap(false); + valid_bytes_offset = i + 1; + } + } + } + UnsafeAppendToBitmap(valid_bytes + valid_bytes_offset, length - valid_bytes_offset); + } else { + if (have_null_value) { + std::vector valid_vector(length, 0); + for (int64_t i = 0; i < length; ++i) { + UnsafeAppendNextOffset(); + if (values[i]) { + value_data_builder_.UnsafeAppend(reinterpret_cast(values[i]), + value_lengths[i]); + valid_vector[i] = 1; + } + } + UnsafeAppendToBitmap(valid_vector.data(), length); + } else { + for (int64_t i = 0; i < length; ++i) { + UnsafeAppendNextOffset(); + value_data_builder_.UnsafeAppend(reinterpret_cast(values[i]), + value_lengths[i]); + } + UnsafeAppendToBitmap(NULLPTR, length); + } + } + return Status::OK(); + } + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + auto bitmap = array.GetValues(0, 0); + auto offsets = array.GetValues(1); + auto data = array.GetValues(2, 0); + auto total_length = offsets[offset + length] - offsets[offset]; + ARROW_RETURN_NOT_OK(Reserve(length)); + ARROW_RETURN_NOT_OK(ReserveData(total_length)); + for (int64_t i = 0; i < length; i++) { + if (!bitmap || bit_util::GetBit(bitmap, array.offset + offset + i)) { + const offset_type start = offsets[offset + i]; + const offset_type end = offsets[offset + i + 1]; + UnsafeAppend(data + start, end - start); + } else { + UnsafeAppendNull(); + } + } + return Status::OK(); + } + + void Reset() override { + ArrayBuilder::Reset(); + offsets_builder_.Reset(); + value_data_builder_.Reset(); + } + + Status ValidateOverflow(int64_t new_bytes) { + auto new_size = value_data_builder_.length() + new_bytes; + if (ARROW_PREDICT_FALSE(new_size > memory_limit())) { + return Status::CapacityError("array cannot contain more than ", memory_limit(), + " bytes, have ", new_size); + } else { + return Status::OK(); + } + } + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + // One more than requested for offsets + ARROW_RETURN_NOT_OK(offsets_builder_.Resize(capacity + 1)); + return ArrayBuilder::Resize(capacity); + } + + /// \brief Ensures there is enough allocated capacity to append the indicated + /// number of bytes to the value data buffer without additional allocations + Status ReserveData(int64_t elements) { + ARROW_RETURN_NOT_OK(ValidateOverflow(elements)); + return value_data_builder_.Reserve(elements); + } + + Status FinishInternal(std::shared_ptr* out) override { + // Write final offset (values length) + ARROW_RETURN_NOT_OK(AppendNextOffset()); + + // These buffers' padding zeroed by BufferBuilder + std::shared_ptr offsets, value_data, null_bitmap; + ARROW_RETURN_NOT_OK(offsets_builder_.Finish(&offsets)); + ARROW_RETURN_NOT_OK(value_data_builder_.Finish(&value_data)); + ARROW_RETURN_NOT_OK(null_bitmap_builder_.Finish(&null_bitmap)); + + *out = ArrayData::Make(type(), length_, {null_bitmap, offsets, value_data}, + null_count_, 0); + Reset(); + return Status::OK(); + } + + /// \return data pointer of the value date builder + const uint8_t* value_data() const { return value_data_builder_.data(); } + /// \return size of values buffer so far + int64_t value_data_length() const { return value_data_builder_.length(); } + /// \return capacity of values buffer + int64_t value_data_capacity() const { return value_data_builder_.capacity(); } + + /// \return data pointer of the value date builder + const offset_type* offsets_data() const { return offsets_builder_.data(); } + + /// Temporary access to a value. + /// + /// This pointer becomes invalid on the next modifying operation. + const uint8_t* GetValue(int64_t i, offset_type* out_length) const { + const offset_type* offsets = offsets_builder_.data(); + const auto offset = offsets[i]; + if (i == (length_ - 1)) { + *out_length = static_cast(value_data_builder_.length()) - offset; + } else { + *out_length = offsets[i + 1] - offset; + } + return value_data_builder_.data() + offset; + } + + offset_type offset(int64_t i) const { return offsets_data()[i]; } + + /// Temporary access to a value. + /// + /// This view becomes invalid on the next modifying operation. + std::string_view GetView(int64_t i) const { + offset_type value_length; + const uint8_t* value_data = GetValue(i, &value_length); + return std::string_view(reinterpret_cast(value_data), value_length); + } + + // Cannot make this a static attribute because of linking issues + static constexpr int64_t memory_limit() { + return std::numeric_limits::max() - 1; + } + + protected: + TypedBufferBuilder offsets_builder_; + TypedBufferBuilder value_data_builder_; + + Status AppendNextOffset() { + const int64_t num_bytes = value_data_builder_.length(); + return offsets_builder_.Append(static_cast(num_bytes)); + } + + void UnsafeAppendNextOffset() { + const int64_t num_bytes = value_data_builder_.length(); + offsets_builder_.UnsafeAppend(static_cast(num_bytes)); + } +}; + +/// \class BinaryBuilder +/// \brief Builder class for variable-length binary data +class ARROW_EXPORT BinaryBuilder : public BaseBinaryBuilder { + public: + using BaseBinaryBuilder::BaseBinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return binary(); } +}; + +/// \class StringBuilder +/// \brief Builder class for UTF8 strings +class ARROW_EXPORT StringBuilder : public BinaryBuilder { + public: + using BinaryBuilder::BinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return utf8(); } +}; + +/// \class LargeBinaryBuilder +/// \brief Builder class for large variable-length binary data +class ARROW_EXPORT LargeBinaryBuilder : public BaseBinaryBuilder { + public: + using BaseBinaryBuilder::BaseBinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return large_binary(); } +}; + +/// \class LargeStringBuilder +/// \brief Builder class for large UTF8 strings +class ARROW_EXPORT LargeStringBuilder : public LargeBinaryBuilder { + public: + using LargeBinaryBuilder::LargeBinaryBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return large_utf8(); } +}; + +// ---------------------------------------------------------------------- +// BinaryViewBuilder, StringViewBuilder +// +// These builders do not support building raw pointer view arrays. + +namespace internal { + +// We allocate medium-sized memory chunks and accumulate data in those, which +// may result in some waste if there are many large-ish strings. If a string +// comes along that does not fit into a block, we allocate a new block and +// write into that. +// +// Later we can implement optimizations to continuing filling underfull blocks +// after encountering a large string that required allocating a new block. +class ARROW_EXPORT StringHeapBuilder { + public: + static constexpr int64_t kDefaultBlocksize = 32 << 10; // 32KB + + StringHeapBuilder(MemoryPool* pool, int64_t alignment) + : pool_(pool), alignment_(alignment) {} + + void SetBlockSize(int64_t blocksize) { blocksize_ = blocksize; } + + using c_type = BinaryViewType::c_type; + + template + std::conditional_t, c_type> Append(const uint8_t* value, + int64_t length) { + if (length <= BinaryViewType::kInlineSize) { + return util::ToInlineBinaryView(value, static_cast(length)); + } + + if constexpr (Safe) { + ARROW_RETURN_NOT_OK(Reserve(length)); + } + + auto v = util::ToNonInlineBinaryView(value, static_cast(length), + static_cast(blocks_.size() - 1), + current_offset_); + + memcpy(current_out_buffer_, value, static_cast(length)); + current_out_buffer_ += length; + current_remaining_bytes_ -= length; + current_offset_ += static_cast(length); + return v; + } + + static constexpr int64_t ValueSizeLimit() { + return std::numeric_limits::max(); + } + + /// \brief Ensure that the indicated number of bytes can be appended via + /// UnsafeAppend operations without the need to allocate more memory + Status Reserve(int64_t num_bytes) { + if (ARROW_PREDICT_FALSE(num_bytes > ValueSizeLimit())) { + return Status::CapacityError( + "BinaryView or StringView elements cannot reference " + "strings larger than 2GB"); + } + if (num_bytes > current_remaining_bytes_) { + ARROW_RETURN_NOT_OK(FinishLastBlock()); + current_remaining_bytes_ = num_bytes > blocksize_ ? num_bytes : blocksize_; + ARROW_ASSIGN_OR_RAISE( + std::shared_ptr new_block, + AllocateResizableBuffer(current_remaining_bytes_, alignment_, pool_)); + current_offset_ = 0; + current_out_buffer_ = new_block->mutable_data(); + blocks_.emplace_back(std::move(new_block)); + } + return Status::OK(); + } + + void Reset() { + current_offset_ = 0; + current_out_buffer_ = NULLPTR; + current_remaining_bytes_ = 0; + blocks_.clear(); + } + + int64_t current_remaining_bytes() const { return current_remaining_bytes_; } + + Result>> Finish() { + if (!blocks_.empty()) { + ARROW_RETURN_NOT_OK(FinishLastBlock()); + } + current_offset_ = 0; + current_out_buffer_ = NULLPTR; + current_remaining_bytes_ = 0; + return std::move(blocks_); + } + + private: + Status FinishLastBlock() { + if (current_remaining_bytes_ > 0) { + // Avoid leaking uninitialized bytes from the allocator + ARROW_RETURN_NOT_OK( + blocks_.back()->Resize(blocks_.back()->size() - current_remaining_bytes_, + /*shrink_to_fit=*/true)); + blocks_.back()->ZeroPadding(); + } + return Status::OK(); + } + + MemoryPool* pool_; + int64_t alignment_; + int64_t blocksize_ = kDefaultBlocksize; + std::vector> blocks_; + + int32_t current_offset_ = 0; + uint8_t* current_out_buffer_ = NULLPTR; + int64_t current_remaining_bytes_ = 0; +}; + +} // namespace internal + +class ARROW_EXPORT BinaryViewBuilder : public ArrayBuilder { + public: + using TypeClass = BinaryViewType; + + // this constructor provided for MakeBuilder compatibility + BinaryViewBuilder(const std::shared_ptr&, MemoryPool* pool); + + explicit BinaryViewBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + data_builder_(pool, alignment), + data_heap_builder_(pool, alignment) {} + + /// Set the size for future preallocated data buffers. + /// + /// The default size is 32KB, so after each 32KB of string data appended to the builder + /// a new data buffer will be allocated. Adjust this to a larger value to decrease the + /// frequency of allocation, or to a smaller value to lower the overhead of each + /// allocation. + void SetBlockSize(int64_t blocksize) { data_heap_builder_.SetBlockSize(blocksize); } + + /// The number of bytes which can be appended to this builder without allocating another + /// data buffer. + int64_t current_block_bytes_remaining() const { + return data_heap_builder_.current_remaining_bytes(); + } + + Status Append(const uint8_t* value, int64_t length) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendToBitmap(true); + ARROW_ASSIGN_OR_RAISE(auto v, + data_heap_builder_.Append(value, length)); + data_builder_.UnsafeAppend(v); + return Status::OK(); + } + + Status Append(const char* value, int64_t length) { + return Append(reinterpret_cast(value), length); + } + + Status Append(std::string_view value) { + return Append(value.data(), static_cast(value.size())); + } + + /// \brief Append without checking capacity + /// + /// Builder should have been presized using Reserve() and ReserveData(), + /// respectively, and the value must not be larger than 2GB + void UnsafeAppend(const uint8_t* value, int64_t length) { + UnsafeAppendToBitmap(true); + auto v = data_heap_builder_.Append(value, length); + data_builder_.UnsafeAppend(v); + } + + void UnsafeAppend(const char* value, int64_t length) { + UnsafeAppend(reinterpret_cast(value), length); + } + + void UnsafeAppend(const std::string& value) { + UnsafeAppend(value.c_str(), static_cast(value.size())); + } + + void UnsafeAppend(std::string_view value) { + UnsafeAppend(value.data(), static_cast(value.size())); + } + + /// \brief Ensures there is enough allocated available capacity in the + /// out-of-line data heap to append the indicated number of bytes without + /// additional allocations + Status ReserveData(int64_t length); + + Status AppendNulls(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, BinaryViewType::c_type{}); + UnsafeSetNull(length); + return Status::OK(); + } + + /// \brief Append a single null element + Status AppendNull() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(false); + return Status::OK(); + } + + /// \brief Append a empty element (length-0 inline string) + Status AppendEmptyValue() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(true); + return Status::OK(); + } + + /// \brief Append several empty elements + Status AppendEmptyValues(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, BinaryViewType::c_type{}); + UnsafeSetNotNull(length); + return Status::OK(); + } + + void UnsafeAppendNull() { + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(false); + } + + void UnsafeAppendEmptyValue() { + data_builder_.UnsafeAppend(BinaryViewType::c_type{}); + UnsafeAppendToBitmap(true); + } + + /// \brief Append a slice of a BinaryViewArray passed as an ArraySpan. Copies + /// the underlying out-of-line string memory to avoid memory lifetime issues + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override; + + void Reset() override; + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + capacity = std::max(capacity, kMinBuilderCapacity); + ARROW_RETURN_NOT_OK(data_builder_.Resize(capacity)); + return ArrayBuilder::Resize(capacity); + } + + Status FinishInternal(std::shared_ptr* out) override; + + std::shared_ptr type() const override { return binary_view(); } + + protected: + TypedBufferBuilder data_builder_; + + // Accumulates out-of-line data in fixed-size chunks which are then attached + // to the resulting ArrayData + internal::StringHeapBuilder data_heap_builder_; +}; + +class ARROW_EXPORT StringViewBuilder : public BinaryViewBuilder { + public: + using BinaryViewBuilder::BinaryViewBuilder; + std::shared_ptr type() const override { return utf8_view(); } +}; + +// ---------------------------------------------------------------------- +// FixedSizeBinaryBuilder + +class ARROW_EXPORT FixedSizeBinaryBuilder : public ArrayBuilder { + public: + using TypeClass = FixedSizeBinaryType; + + explicit FixedSizeBinaryBuilder(const std::shared_ptr& type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + Status Append(const uint8_t* value) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(value); + return Status::OK(); + } + + Status Append(const char* value) { + return Append(reinterpret_cast(value)); + } + + Status Append(std::string_view view) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(view); + return Status::OK(); + } + + Status Append(const std::string& s) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(s); + return Status::OK(); + } + + Status Append(const Buffer& s) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(s); + return Status::OK(); + } + + Status Append(const std::shared_ptr& s) { return Append(*s); } + + template + Status Append(const std::array& value) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend( + std::string_view(reinterpret_cast(value.data()), value.size())); + return Status::OK(); + } + + Status AppendValues(const uint8_t* data, int64_t length, + const uint8_t* valid_bytes = NULLPTR); + + Status AppendValues(const uint8_t* data, int64_t length, const uint8_t* validity, + int64_t bitmap_offset); + + Status AppendNull() final; + Status AppendNulls(int64_t length) final; + + Status AppendEmptyValue() final; + Status AppendEmptyValues(int64_t length) final; + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + return AppendValues( + array.GetValues(1, 0) + ((array.offset + offset) * byte_width_), length, + array.GetValues(0, 0), array.offset + offset); + } + + void UnsafeAppend(const uint8_t* value) { + UnsafeAppendToBitmap(true); + if (ARROW_PREDICT_TRUE(byte_width_ > 0)) { + byte_builder_.UnsafeAppend(value, byte_width_); + } + } + + void UnsafeAppend(const char* value) { + UnsafeAppend(reinterpret_cast(value)); + } + + void UnsafeAppend(std::string_view value) { +#ifndef NDEBUG + CheckValueSize(static_cast(value.size())); +#endif + UnsafeAppend(reinterpret_cast(value.data())); + } + + void UnsafeAppend(const Buffer& s) { UnsafeAppend(std::string_view{s}); } + + void UnsafeAppend(const std::shared_ptr& s) { UnsafeAppend(*s); } + + void UnsafeAppendNull() { + UnsafeAppendToBitmap(false); + byte_builder_.UnsafeAppend(/*num_copies=*/byte_width_, 0); + } + + Status ValidateOverflow(int64_t new_bytes) const { + auto new_size = byte_builder_.length() + new_bytes; + if (ARROW_PREDICT_FALSE(new_size > memory_limit())) { + return Status::CapacityError("array cannot contain more than ", memory_limit(), + " bytes, have ", new_size); + } else { + return Status::OK(); + } + } + + /// \brief Ensures there is enough allocated capacity to append the indicated + /// number of bytes to the value data buffer without additional allocations + Status ReserveData(int64_t elements) { + ARROW_RETURN_NOT_OK(ValidateOverflow(elements)); + return byte_builder_.Reserve(elements); + } + + void Reset() override; + Status Resize(int64_t capacity) override; + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \return size of values buffer so far + int64_t value_data_length() const { return byte_builder_.length(); } + + int32_t byte_width() const { return byte_width_; } + + /// Temporary access to a value. + /// + /// This pointer becomes invalid on the next modifying operation. + const uint8_t* GetValue(int64_t i) const; + + /// Temporary mutable access to a value. + /// + /// This pointer becomes invalid on the next modifying operation. + uint8_t* GetMutableValue(int64_t i) { + uint8_t* data_ptr = byte_builder_.mutable_data(); + return data_ptr + i * byte_width_; + } + + /// Temporary mutable access to a value. + /// + /// This view becomes invalid on the next modifying operation. + std::string_view GetView(int64_t i) const; + + /// Advance builder without allocating nor writing any values + /// + /// The internal pointer is advanced by `length` values and the same number + /// of non-null entries are appended to the validity bitmap. + /// This method assumes that the `length` values were populated directly, + /// for example using `GetMutableValue`. + void UnsafeAdvance(int64_t length) { + byte_builder_.UnsafeAdvance(length * byte_width_); + UnsafeAppendToBitmap(length, true); + } + + /// Advance builder without allocating nor writing any values + /// + /// The internal pointer is advanced by `length` values and the same number + /// of validity bits are appended to the validity bitmap. + /// This method assumes that the `length` values were populated directly, + /// for example using `GetMutableValue`. + void UnsafeAdvance(int64_t length, const uint8_t* validity, int64_t valid_bits_offset) { + byte_builder_.UnsafeAdvance(length * byte_width_); + UnsafeAppendToBitmap(validity, valid_bits_offset, length); + } + + static constexpr int64_t memory_limit() { + return std::numeric_limits::max() - 1; + } + + std::shared_ptr type() const override { + return fixed_size_binary(byte_width_); + } + + protected: + int32_t byte_width_; + BufferBuilder byte_builder_; + + void CheckValueSize(int64_t size); +}; + +/// @} + +// ---------------------------------------------------------------------- +// Chunked builders: build a sequence of BinaryArray or StringArray that are +// limited to a particular size (to the upper limit of 2GB) + +namespace internal { + +class ARROW_EXPORT ChunkedBinaryBuilder { + public: + explicit ChunkedBinaryBuilder(int32_t max_chunk_value_length, + MemoryPool* pool = default_memory_pool()); + + ChunkedBinaryBuilder(int32_t max_chunk_value_length, int32_t max_chunk_length, + MemoryPool* pool = default_memory_pool()); + + virtual ~ChunkedBinaryBuilder() = default; + + Status Append(const uint8_t* value, int32_t length) { + if (ARROW_PREDICT_FALSE(length + builder_->value_data_length() > + max_chunk_value_length_)) { + if (builder_->value_data_length() == 0) { + // The current item is larger than max_chunk_size_; + // this chunk will be oversize and hold *only* this item + ARROW_RETURN_NOT_OK(builder_->Append(value, length)); + return NextChunk(); + } + // The current item would cause builder_->value_data_length() to exceed + // max_chunk_size_, so finish this chunk and append the current item to the next + // chunk + ARROW_RETURN_NOT_OK(NextChunk()); + return Append(value, length); + } + + if (ARROW_PREDICT_FALSE(builder_->length() == max_chunk_length_)) { + // The current item would cause builder_->length() to exceed max_chunk_length_, so + // finish this chunk and append the current item to the next chunk + ARROW_RETURN_NOT_OK(NextChunk()); + } + + return builder_->Append(value, length); + } + + Status Append(std::string_view value) { + return Append(reinterpret_cast(value.data()), + static_cast(value.size())); + } + + Status AppendNull() { + if (ARROW_PREDICT_FALSE(builder_->length() == max_chunk_length_)) { + ARROW_RETURN_NOT_OK(NextChunk()); + } + return builder_->AppendNull(); + } + + Status Reserve(int64_t values); + + virtual Status Finish(ArrayVector* out); + + protected: + Status NextChunk(); + + // maximum total character data size per chunk + int64_t max_chunk_value_length_; + + // maximum elements allowed per chunk + int64_t max_chunk_length_ = kListMaximumElements; + + // when Reserve() would cause builder_ to exceed its max_chunk_length_, + // add to extra_capacity_ instead and wait to reserve until the next chunk + int64_t extra_capacity_ = 0; + + std::unique_ptr builder_; + std::vector> chunks_; +}; + +class ARROW_EXPORT ChunkedStringBuilder : public ChunkedBinaryBuilder { + public: + using ChunkedBinaryBuilder::ChunkedBinaryBuilder; + + Status Finish(ArrayVector* out) override; +}; + +} // namespace internal + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_decimal.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_decimal.h new file mode 100644 index 0000000000000000000000000000000000000000..a0bf0a04220842cceada0d0754ad6be4e41a3093 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_decimal.h @@ -0,0 +1,164 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/array/array_decimal.h" +#include "arrow/array/builder_base.h" +#include "arrow/array/builder_binary.h" +#include "arrow/array/data.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup numeric-builders +/// +/// @{ + +class ARROW_EXPORT Decimal32Builder : public FixedSizeBinaryBuilder { + public: + using TypeClass = Decimal32Type; + using ValueType = Decimal32; + + explicit Decimal32Builder(const std::shared_ptr& type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + using FixedSizeBinaryBuilder::Append; + using FixedSizeBinaryBuilder::AppendValues; + using FixedSizeBinaryBuilder::Reset; + + Status Append(Decimal32 val); + void UnsafeAppend(Decimal32 val); + void UnsafeAppend(std::string_view val); + + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return decimal_type_; } + + protected: + std::shared_ptr decimal_type_; +}; + +class ARROW_EXPORT Decimal64Builder : public FixedSizeBinaryBuilder { + public: + using TypeClass = Decimal64Type; + using ValueType = Decimal64; + + explicit Decimal64Builder(const std::shared_ptr& type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + using FixedSizeBinaryBuilder::Append; + using FixedSizeBinaryBuilder::AppendValues; + using FixedSizeBinaryBuilder::Reset; + + Status Append(Decimal64 val); + void UnsafeAppend(Decimal64 val); + void UnsafeAppend(std::string_view val); + + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return decimal_type_; } + + protected: + std::shared_ptr decimal_type_; +}; + +class ARROW_EXPORT Decimal128Builder : public FixedSizeBinaryBuilder { + public: + using TypeClass = Decimal128Type; + using ValueType = Decimal128; + + explicit Decimal128Builder(const std::shared_ptr& type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + using FixedSizeBinaryBuilder::Append; + using FixedSizeBinaryBuilder::AppendValues; + using FixedSizeBinaryBuilder::Reset; + + Status Append(Decimal128 val); + void UnsafeAppend(Decimal128 val); + void UnsafeAppend(std::string_view val); + + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return decimal_type_; } + + protected: + std::shared_ptr decimal_type_; +}; + +class ARROW_EXPORT Decimal256Builder : public FixedSizeBinaryBuilder { + public: + using TypeClass = Decimal256Type; + using ValueType = Decimal256; + + explicit Decimal256Builder(const std::shared_ptr& type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + using FixedSizeBinaryBuilder::Append; + using FixedSizeBinaryBuilder::AppendValues; + using FixedSizeBinaryBuilder::Reset; + + Status Append(const Decimal256& val); + void UnsafeAppend(const Decimal256& val); + void UnsafeAppend(std::string_view val); + + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { return decimal_type_; } + + protected: + std::shared_ptr decimal_type_; +}; + +using DecimalBuilder = Decimal128Builder; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_dict.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_dict.h new file mode 100644 index 0000000000000000000000000000000000000000..116c82049eea9ea49a716452090297f57be4eb6b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_dict.h @@ -0,0 +1,728 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/array_binary.h" +#include "arrow/array/builder_adaptive.h" // IWYU pragma: export +#include "arrow/array/builder_base.h" // IWYU pragma: export +#include "arrow/array/builder_primitive.h" // IWYU pragma: export +#include "arrow/array/data.h" +#include "arrow/array/util.h" +#include "arrow/scalar.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/bit_block_counter.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/decimal.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +// ---------------------------------------------------------------------- +// Dictionary builder + +namespace internal { + +template +struct DictionaryValue { + using type = typename T::c_type; + using PhysicalType = T; +}; + +template +struct DictionaryValue> { + using type = std::string_view; + using PhysicalType = + typename std::conditional::value, + BinaryType, LargeBinaryType>::type; +}; + +template +struct DictionaryValue> { + using type = std::string_view; + using PhysicalType = BinaryViewType; +}; + +template +struct DictionaryValue> { + using type = std::string_view; + using PhysicalType = BinaryType; +}; + +class ARROW_EXPORT DictionaryMemoTable { + public: + DictionaryMemoTable(MemoryPool* pool, const std::shared_ptr& type); + DictionaryMemoTable(MemoryPool* pool, const std::shared_ptr& dictionary); + ~DictionaryMemoTable(); + + Status GetArrayData(int64_t start_offset, std::shared_ptr* out); + + /// \brief Insert new memo values + Status InsertValues(const Array& values); + + int32_t size() const; + + template + Status GetOrInsert(typename DictionaryValue::type value, int32_t* out) { + // We want to keep the DictionaryMemoTable implementation private, also we can't + // use extern template classes because of compiler issues (MinGW?). Instead, + // we expose explicit function overrides for each supported physical type. + const typename DictionaryValue::PhysicalType* physical_type = NULLPTR; + return GetOrInsert(physical_type, value, out); + } + + private: + Status GetOrInsert(const BooleanType*, bool value, int32_t* out); + Status GetOrInsert(const Int8Type*, int8_t value, int32_t* out); + Status GetOrInsert(const Int16Type*, int16_t value, int32_t* out); + Status GetOrInsert(const Int32Type*, int32_t value, int32_t* out); + Status GetOrInsert(const Int64Type*, int64_t value, int32_t* out); + Status GetOrInsert(const UInt8Type*, uint8_t value, int32_t* out); + Status GetOrInsert(const UInt16Type*, uint16_t value, int32_t* out); + Status GetOrInsert(const UInt32Type*, uint32_t value, int32_t* out); + Status GetOrInsert(const UInt64Type*, uint64_t value, int32_t* out); + Status GetOrInsert(const DurationType*, int64_t value, int32_t* out); + Status GetOrInsert(const TimestampType*, int64_t value, int32_t* out); + Status GetOrInsert(const Date32Type*, int32_t value, int32_t* out); + Status GetOrInsert(const Date64Type*, int64_t value, int32_t* out); + Status GetOrInsert(const Time32Type*, int32_t value, int32_t* out); + Status GetOrInsert(const Time64Type*, int64_t value, int32_t* out); + Status GetOrInsert(const MonthDayNanoIntervalType*, + MonthDayNanoIntervalType::MonthDayNanos value, int32_t* out); + Status GetOrInsert(const DayTimeIntervalType*, + DayTimeIntervalType::DayMilliseconds value, int32_t* out); + Status GetOrInsert(const MonthIntervalType*, int32_t value, int32_t* out); + Status GetOrInsert(const FloatType*, float value, int32_t* out); + Status GetOrInsert(const DoubleType*, double value, int32_t* out); + + Status GetOrInsert(const BinaryType*, std::string_view value, int32_t* out); + Status GetOrInsert(const LargeBinaryType*, std::string_view value, int32_t* out); + Status GetOrInsert(const BinaryViewType*, std::string_view value, int32_t* out); + + class DictionaryMemoTableImpl; + std::unique_ptr impl_; +}; + +} // namespace internal + +/// \addtogroup dictionary-builders +/// +/// @{ + +namespace internal { + +/// \brief Array builder for created encoded DictionaryArray from +/// dense array +/// +/// Unlike other builders, dictionary builder does not completely +/// reset the state on Finish calls. +template +class DictionaryBuilderBase : public ArrayBuilder { + public: + using TypeClass = DictionaryType; + using Value = typename DictionaryValue::type; + + // WARNING: the type given below is the value type, not the DictionaryType. + // The DictionaryType is instantiated on the Finish() call. + template + DictionaryBuilderBase(uint8_t start_int_size, + enable_if_t::value && + !is_fixed_size_binary_type::value, + const std::shared_ptr&> + value_type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + memo_table_(new internal::DictionaryMemoTable(pool, value_type)), + delta_offset_(0), + byte_width_(-1), + indices_builder_(start_int_size, pool, alignment), + value_type_(value_type) {} + + template + explicit DictionaryBuilderBase( + enable_if_t::value, const std::shared_ptr&> + value_type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + memo_table_(new internal::DictionaryMemoTable(pool, value_type)), + delta_offset_(0), + byte_width_(-1), + indices_builder_(pool, alignment), + value_type_(value_type) {} + + template + explicit DictionaryBuilderBase( + const std::shared_ptr& index_type, + enable_if_t::value, const std::shared_ptr&> + value_type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + memo_table_(new internal::DictionaryMemoTable(pool, value_type)), + delta_offset_(0), + byte_width_(-1), + indices_builder_(index_type, pool, alignment), + value_type_(value_type) {} + + template + DictionaryBuilderBase(uint8_t start_int_size, + enable_if_t::value && + is_fixed_size_binary_type::value, + const std::shared_ptr&> + value_type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + memo_table_(new internal::DictionaryMemoTable(pool, value_type)), + delta_offset_(0), + byte_width_(static_cast(*value_type).byte_width()), + indices_builder_(start_int_size, pool, alignment), + value_type_(value_type) {} + + template + explicit DictionaryBuilderBase( + enable_if_fixed_size_binary&> value_type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + memo_table_(new internal::DictionaryMemoTable(pool, value_type)), + delta_offset_(0), + byte_width_(static_cast(*value_type).byte_width()), + indices_builder_(pool, alignment), + value_type_(value_type) {} + + template + explicit DictionaryBuilderBase( + const std::shared_ptr& index_type, + enable_if_fixed_size_binary&> value_type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + memo_table_(new internal::DictionaryMemoTable(pool, value_type)), + delta_offset_(0), + byte_width_(static_cast(*value_type).byte_width()), + indices_builder_(index_type, pool, alignment), + value_type_(value_type) {} + + template + explicit DictionaryBuilderBase( + enable_if_parameter_free pool = default_memory_pool()) + : DictionaryBuilderBase(TypeTraits::type_singleton(), pool) {} + + // This constructor doesn't check for errors. Use InsertMemoValues instead. + explicit DictionaryBuilderBase(const std::shared_ptr& dictionary, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + memo_table_(new internal::DictionaryMemoTable(pool, dictionary)), + delta_offset_(0), + byte_width_(-1), + indices_builder_(pool, alignment), + value_type_(dictionary->type()) {} + + ~DictionaryBuilderBase() override = default; + + /// \brief The current number of entries in the dictionary + int64_t dictionary_length() const { return memo_table_->size(); } + + /// \brief The value byte width (for FixedSizeBinaryType) + template + enable_if_fixed_size_binary byte_width() const { + return byte_width_; + } + + /// \brief Append a scalar value + Status Append(Value value) { + ARROW_RETURN_NOT_OK(Reserve(1)); + + int32_t memo_index; + ARROW_RETURN_NOT_OK(memo_table_->GetOrInsert(value, &memo_index)); + ARROW_RETURN_NOT_OK(indices_builder_.Append(memo_index)); + length_ += 1; + + return Status::OK(); + } + + /// \brief Append a fixed-width string (only for FixedSizeBinaryType) + template + enable_if_fixed_size_binary Append(const uint8_t* value) { + return Append(std::string_view(reinterpret_cast(value), byte_width_)); + } + + /// \brief Append a fixed-width string (only for FixedSizeBinaryType) + template + enable_if_fixed_size_binary Append(const char* value) { + return Append(std::string_view(value, byte_width_)); + } + + /// \brief Append a string (only for binary types) + template + enable_if_binary_like Append(const uint8_t* value, int32_t length) { + return Append(reinterpret_cast(value), length); + } + + /// \brief Append a string (only for binary types) + template + enable_if_binary_like Append(const char* value, int32_t length) { + return Append(std::string_view(value, length)); + } + + /// \brief Append a string (only for string types) + template + enable_if_string_like Append(const char* value, int32_t length) { + return Append(std::string_view(value, length)); + } + + /// \brief Append a decimal (only for Decimal32/64/128/256 Type) + template ::CType> + enable_if_decimal Append(const CType& value) { + auto bytes = value.ToBytes(); + return Append(bytes.data(), static_cast(bytes.size())); + } + + /// \brief Append a scalar null value + Status AppendNull() final { + length_ += 1; + null_count_ += 1; + + return indices_builder_.AppendNull(); + } + + Status AppendNulls(int64_t length) final { + length_ += length; + null_count_ += length; + + return indices_builder_.AppendNulls(length); + } + + Status AppendEmptyValue() final { + length_ += 1; + + return indices_builder_.AppendEmptyValue(); + } + + Status AppendEmptyValues(int64_t length) final { + length_ += length; + + return indices_builder_.AppendEmptyValues(length); + } + + Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override { + if (!scalar.is_valid) return AppendNulls(n_repeats); + + const auto& dict_ty = internal::checked_cast(*scalar.type); + const DictionaryScalar& dict_scalar = + internal::checked_cast(scalar); + const auto& dict = internal::checked_cast::ArrayType&>( + *dict_scalar.value.dictionary); + ARROW_RETURN_NOT_OK(Reserve(n_repeats)); + switch (dict_ty.index_type()->id()) { + case Type::UINT8: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + case Type::INT8: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + case Type::UINT16: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + case Type::INT16: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + case Type::UINT32: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + case Type::INT32: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + case Type::UINT64: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + case Type::INT64: + return AppendScalarImpl(dict, *dict_scalar.value.index, n_repeats); + default: + return Status::TypeError("Invalid index type: ", dict_ty); + } + return Status::OK(); + } + + Status AppendScalars(const ScalarVector& scalars) override { + for (const auto& scalar : scalars) { + ARROW_RETURN_NOT_OK(AppendScalar(*scalar, /*n_repeats=*/1)); + } + return Status::OK(); + } + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length) final { + // Visit the indices and insert the unpacked values. + const auto& dict_ty = internal::checked_cast(*array.type); + // See if possible to avoid using ToArrayData here + const typename TypeTraits::ArrayType dict(array.dictionary().ToArrayData()); + ARROW_RETURN_NOT_OK(Reserve(length)); + switch (dict_ty.index_type()->id()) { + case Type::UINT8: + return AppendArraySliceImpl(dict, array, offset, length); + case Type::INT8: + return AppendArraySliceImpl(dict, array, offset, length); + case Type::UINT16: + return AppendArraySliceImpl(dict, array, offset, length); + case Type::INT16: + return AppendArraySliceImpl(dict, array, offset, length); + case Type::UINT32: + return AppendArraySliceImpl(dict, array, offset, length); + case Type::INT32: + return AppendArraySliceImpl(dict, array, offset, length); + case Type::UINT64: + return AppendArraySliceImpl(dict, array, offset, length); + case Type::INT64: + return AppendArraySliceImpl(dict, array, offset, length); + default: + return Status::TypeError("Invalid index type: ", dict_ty); + } + return Status::OK(); + } + + /// \brief Insert values into the dictionary's memo, but do not append any + /// indices. Can be used to initialize a new builder with known dictionary + /// values + /// \param[in] values dictionary values to add to memo. Type must match + /// builder type + Status InsertMemoValues(const Array& values) { + return memo_table_->InsertValues(values); + } + + /// \brief Append a whole dense array to the builder + template + enable_if_t::value, Status> AppendArray( + const Array& array) { + using ArrayType = typename TypeTraits::ArrayType; + +#ifndef NDEBUG + ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType( + value_type_, array, "Wrong value type of array to be appended")); +#endif + + const auto& concrete_array = static_cast(array); + for (int64_t i = 0; i < array.length(); i++) { + if (array.IsNull(i)) { + ARROW_RETURN_NOT_OK(AppendNull()); + } else { + ARROW_RETURN_NOT_OK(Append(concrete_array.GetView(i))); + } + } + return Status::OK(); + } + + template + enable_if_fixed_size_binary AppendArray(const Array& array) { +#ifndef NDEBUG + ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType( + value_type_, array, "Wrong value type of array to be appended")); +#endif + + const auto& concrete_array = static_cast(array); + for (int64_t i = 0; i < array.length(); i++) { + if (array.IsNull(i)) { + ARROW_RETURN_NOT_OK(AppendNull()); + } else { + ARROW_RETURN_NOT_OK(Append(concrete_array.GetValue(i))); + } + } + return Status::OK(); + } + + void Reset() override { + // Perform a partial reset. Call ResetFull to also reset the accumulated + // dictionary values + ArrayBuilder::Reset(); + indices_builder_.Reset(); + } + + /// \brief Reset and also clear accumulated dictionary values in memo table + void ResetFull() { + Reset(); + memo_table_.reset(new internal::DictionaryMemoTable(pool_, value_type_)); + } + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + capacity = std::max(capacity, kMinBuilderCapacity); + ARROW_RETURN_NOT_OK(indices_builder_.Resize(capacity)); + capacity_ = indices_builder_.capacity(); + return Status::OK(); + } + + /// \brief Return dictionary indices and a delta dictionary since the last + /// time that Finish or FinishDelta were called, and reset state of builder + /// (except the memo table) + Status FinishDelta(std::shared_ptr* out_indices, + std::shared_ptr* out_delta) { + std::shared_ptr indices_data; + std::shared_ptr delta_data; + ARROW_RETURN_NOT_OK(FinishWithDictOffset(delta_offset_, &indices_data, &delta_data)); + *out_indices = MakeArray(indices_data); + *out_delta = MakeArray(delta_data); + return Status::OK(); + } + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { + return ::arrow::dictionary(indices_builder_.type(), value_type_); + } + + protected: + template + Status AppendArraySliceImpl(const typename TypeTraits::ArrayType& dict, + const ArraySpan& array, int64_t offset, int64_t length) { + const c_type* values = array.GetValues(1) + offset; + return VisitBitBlocks( + array.buffers[0].data, array.offset + offset, length, + [&](const int64_t position) { + const int64_t index = static_cast(values[position]); + if (dict.IsValid(index)) { + return Append(dict.GetView(index)); + } + return AppendNull(); + }, + [&]() { return AppendNull(); }); + } + + template + Status AppendScalarImpl(const typename TypeTraits::ArrayType& dict, + const Scalar& index_scalar, int64_t n_repeats) { + using ScalarType = typename TypeTraits::ScalarType; + const auto index = internal::checked_cast(index_scalar).value; + if (index_scalar.is_valid && dict.IsValid(index)) { + const auto& value = dict.GetView(index); + for (int64_t i = 0; i < n_repeats; i++) { + ARROW_RETURN_NOT_OK(Append(value)); + } + return Status::OK(); + } + return AppendNulls(n_repeats); + } + + Status FinishInternal(std::shared_ptr* out) override { + std::shared_ptr dictionary; + ARROW_RETURN_NOT_OK(FinishWithDictOffset(/*offset=*/0, out, &dictionary)); + + // Set type of array data to the right dictionary type + (*out)->type = type(); + (*out)->dictionary = dictionary; + return Status::OK(); + } + + Status FinishWithDictOffset(int64_t dict_offset, + std::shared_ptr* out_indices, + std::shared_ptr* out_dictionary) { + // Finalize indices array + ARROW_RETURN_NOT_OK(indices_builder_.FinishInternal(out_indices)); + + // Generate dictionary array from hash table contents + ARROW_RETURN_NOT_OK(memo_table_->GetArrayData(dict_offset, out_dictionary)); + delta_offset_ = memo_table_->size(); + + // Update internals for further uses of this DictionaryBuilder + ArrayBuilder::Reset(); + return Status::OK(); + } + + std::unique_ptr memo_table_; + + // The size of the dictionary memo at last invocation of Finish, to use in + // FinishDelta for computing dictionary deltas + int32_t delta_offset_; + + // Only used for FixedSizeBinaryType + int32_t byte_width_; + + BuilderType indices_builder_; + std::shared_ptr value_type_; +}; + +template +class DictionaryBuilderBase : public ArrayBuilder { + public: + template + DictionaryBuilderBase( + enable_if_t::value, uint8_t> + start_int_size, + const std::shared_ptr& value_type, + MemoryPool* pool = default_memory_pool()) + : ArrayBuilder(pool), indices_builder_(start_int_size, pool) {} + + explicit DictionaryBuilderBase(const std::shared_ptr& value_type, + MemoryPool* pool = default_memory_pool()) + : ArrayBuilder(pool), indices_builder_(pool) {} + + explicit DictionaryBuilderBase(const std::shared_ptr& index_type, + const std::shared_ptr& value_type, + MemoryPool* pool = default_memory_pool()) + : ArrayBuilder(pool), indices_builder_(index_type, pool) {} + + template + explicit DictionaryBuilderBase( + enable_if_t::value, uint8_t> + start_int_size, + MemoryPool* pool = default_memory_pool()) + : ArrayBuilder(pool), indices_builder_(start_int_size, pool) {} + + explicit DictionaryBuilderBase(MemoryPool* pool = default_memory_pool()) + : ArrayBuilder(pool), indices_builder_(pool) {} + + explicit DictionaryBuilderBase(const std::shared_ptr& dictionary, + MemoryPool* pool = default_memory_pool()) + : ArrayBuilder(pool), indices_builder_(pool) {} + + /// \brief Append a scalar null value + Status AppendNull() final { + length_ += 1; + null_count_ += 1; + + return indices_builder_.AppendNull(); + } + + Status AppendNulls(int64_t length) final { + length_ += length; + null_count_ += length; + + return indices_builder_.AppendNulls(length); + } + + Status AppendEmptyValue() final { + length_ += 1; + + return indices_builder_.AppendEmptyValue(); + } + + Status AppendEmptyValues(int64_t length) final { + length_ += length; + + return indices_builder_.AppendEmptyValues(length); + } + + /// \brief Append a whole dense array to the builder + Status AppendArray(const Array& array) { +#ifndef NDEBUG + ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType( + Type::NA, array, "Wrong value type of array to be appended")); +#endif + for (int64_t i = 0; i < array.length(); i++) { + ARROW_RETURN_NOT_OK(AppendNull()); + } + return Status::OK(); + } + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + capacity = std::max(capacity, kMinBuilderCapacity); + + ARROW_RETURN_NOT_OK(indices_builder_.Resize(capacity)); + capacity_ = indices_builder_.capacity(); + return Status::OK(); + } + + Status FinishInternal(std::shared_ptr* out) override { + ARROW_RETURN_NOT_OK(indices_builder_.FinishInternal(out)); + (*out)->type = dictionary((*out)->type, null()); + (*out)->dictionary = NullArray(0).data(); + return Status::OK(); + } + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + std::shared_ptr type() const override { + return ::arrow::dictionary(indices_builder_.type(), null()); + } + + protected: + BuilderType indices_builder_; +}; + +} // namespace internal + +/// \brief A DictionaryArray builder that uses AdaptiveIntBuilder to return the +/// smallest index size that can accommodate the dictionary indices +template +class DictionaryBuilder : public internal::DictionaryBuilderBase { + public: + using BASE = internal::DictionaryBuilderBase; + using BASE::BASE; + + /// \brief Append dictionary indices directly without modifying memo + /// + /// NOTE: Experimental API + Status AppendIndices(const int64_t* values, int64_t length, + const uint8_t* valid_bytes = NULLPTR) { + int64_t null_count_before = this->indices_builder_.null_count(); + ARROW_RETURN_NOT_OK(this->indices_builder_.AppendValues(values, length, valid_bytes)); + this->capacity_ = this->indices_builder_.capacity(); + this->length_ += length; + this->null_count_ += this->indices_builder_.null_count() - null_count_before; + return Status::OK(); + } +}; + +/// \brief A DictionaryArray builder that always returns int32 dictionary +/// indices so that data cast to dictionary form will have a consistent index +/// type, e.g. for creating a ChunkedArray +template +class Dictionary32Builder : public internal::DictionaryBuilderBase { + public: + using BASE = internal::DictionaryBuilderBase; + using BASE::BASE; + + /// \brief Append dictionary indices directly without modifying memo + /// + /// NOTE: Experimental API + Status AppendIndices(const int32_t* values, int64_t length, + const uint8_t* valid_bytes = NULLPTR) { + int64_t null_count_before = this->indices_builder_.null_count(); + ARROW_RETURN_NOT_OK(this->indices_builder_.AppendValues(values, length, valid_bytes)); + this->capacity_ = this->indices_builder_.capacity(); + this->length_ += length; + this->null_count_ += this->indices_builder_.null_count() - null_count_before; + return Status::OK(); + } +}; + +// ---------------------------------------------------------------------- +// Binary / Unicode builders +// (compatibility aliases; those used to be derived classes with additional +// Append() overloads, but they have been folded into DictionaryBuilderBase) + +using BinaryDictionaryBuilder = DictionaryBuilder; +using StringDictionaryBuilder = DictionaryBuilder; +using BinaryDictionary32Builder = Dictionary32Builder; +using StringDictionary32Builder = Dictionary32Builder; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_nested.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_nested.h new file mode 100644 index 0000000000000000000000000000000000000000..fdbeb0cd7d17b40b929d2ba73dba6f425d01c968 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_nested.h @@ -0,0 +1,836 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/array/array_nested.h" +#include "arrow/array/builder_base.h" +#include "arrow/array/data.h" +#include "arrow/buffer.h" +#include "arrow/buffer_builder.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup nested-builders +/// +/// @{ + +// ---------------------------------------------------------------------- +// VarLengthListLikeBuilder + +template +class VarLengthListLikeBuilder : public ArrayBuilder { + public: + using TypeClass = TYPE; + using offset_type = typename TypeClass::offset_type; + + /// Use this constructor to incrementally build the value array along with offsets and + /// null bitmap. + VarLengthListLikeBuilder(MemoryPool* pool, + const std::shared_ptr& value_builder, + const std::shared_ptr& type, + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + offsets_builder_(pool, alignment), + value_builder_(value_builder), + value_field_(type->field(0)->WithType(NULLPTR)) {} + + VarLengthListLikeBuilder(MemoryPool* pool, + const std::shared_ptr& value_builder, + int64_t alignment = kDefaultBufferAlignment) + : VarLengthListLikeBuilder(pool, value_builder, + std::make_shared(value_builder->type()), + alignment) {} + + ~VarLengthListLikeBuilder() override = default; + + Status Resize(int64_t capacity) override { + if (ARROW_PREDICT_FALSE(capacity > maximum_elements())) { + return Status::CapacityError(type_name(), + " array cannot reserve space for more than ", + maximum_elements(), " got ", capacity); + } + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + + // One more than requested for list offsets + const int64_t offsets_capacity = + is_list_view(TYPE::type_id) ? capacity : capacity + 1; + ARROW_RETURN_NOT_OK(offsets_builder_.Resize(offsets_capacity)); + return ArrayBuilder::Resize(capacity); + } + + void Reset() override { + ArrayBuilder::Reset(); + offsets_builder_.Reset(); + value_builder_->Reset(); + } + + /// \brief Start a new variable-length list slot + /// + /// This function should be called before appending elements to the + /// value builder. Elements appended to the value builder before this function + /// is called for the first time, will not be members of any list value. + /// + /// After this function is called, list_length elements SHOULD be appended to + /// the values builder. If this contract is violated, the behavior is defined by + /// the concrete builder implementation and SHOULD NOT be relied upon unless + /// the caller is specifically building a [Large]List or [Large]ListView array. + /// + /// For [Large]List arrays, the list slot length will be the number of elements + /// appended to the values builder before the next call to Append* or Finish. For + /// [Large]ListView arrays, the list slot length will be exactly list_length, but if + /// Append* is called before at least list_length elements are appended to the values + /// builder, the current list slot will share elements with the next list + /// slots or an invalid [Large]ListView array will be generated because there + /// aren't enough elements in the values builder to fill the list slots. + /// + /// If you're building a [Large]List and don't need to be compatible + /// with [Large]ListView, then `BaseListBuilder::Append(bool is_valid)` + /// is a simpler API. + /// + /// \pre if is_valid is false, list_length MUST be 0 + /// \param is_valid Whether the new list slot is valid + /// \param list_length The number of elements in the list + Status Append(bool is_valid, int64_t list_length) { + ARROW_RETURN_NOT_OK(Reserve(1)); + assert(is_valid || list_length == 0); + UnsafeAppendToBitmap(is_valid); + UnsafeAppendDimensions(/*offset=*/value_builder_->length(), /*size=*/list_length); + return Status::OK(); + } + + Status AppendNull() final { + // Append() a null list slot with list_length=0. + // + // When building [Large]List arrays, elements being appended to the values builder + // before the next call to Append* or Finish will extend the list slot length, but + // that is totally fine because list arrays admit non-empty null list slots. + // + // In the case of [Large]ListViews that's not a problem either because the + // list slot length remains zero. + return Append(false, 0); + } + + Status AppendNulls(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + UnsafeAppendToBitmap(length, false); + UnsafeAppendEmptyDimensions(/*num_values=*/length); + return Status::OK(); + } + + /// \brief Append an empty list slot + /// + /// \post Another call to Append* or Finish should be made before appending to + /// the values builder to ensure list slot remains empty + Status AppendEmptyValue() final { return Append(true, 0); } + + /// \brief Append an empty list slot + /// + /// \post Another call to Append* or Finish should be made before appending to + /// the values builder to ensure the last list slot remains empty + Status AppendEmptyValues(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + UnsafeAppendToBitmap(length, true); + UnsafeAppendEmptyDimensions(/*num_values=*/length); + return Status::OK(); + } + + /// \brief Vector append + /// + /// For list-array builders, the sizes are inferred from the offsets. + /// BaseListBuilder provides an implementation that doesn't take sizes, but + /// this virtual function allows dispatching calls to both list-array and + /// list-view-array builders (which need the sizes) + /// + /// \param offsets The offsets of the variable-length lists + /// \param sizes The sizes of the variable-length lists + /// \param length The number of offsets, sizes, and validity bits to append + /// \param valid_bytes If passed, valid_bytes is of equal length to values, + /// and any zero byte will be considered as a null for that slot + virtual Status AppendValues(const offset_type* offsets, const offset_type* sizes, + int64_t length, const uint8_t* valid_bytes) = 0; + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + const offset_type* offsets = array.GetValues(1); + [[maybe_unused]] const offset_type* sizes = NULLPTR; + if constexpr (is_list_view(TYPE::type_id)) { + sizes = array.GetValues(2); + } + static_assert(internal::may_have_validity_bitmap(TYPE::type_id)); + const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR; + ARROW_RETURN_NOT_OK(Reserve(length)); + for (int64_t row = offset; row < offset + length; row++) { + const bool is_valid = !validity || bit_util::GetBit(validity, array.offset + row); + int64_t size = 0; + if (is_valid) { + if constexpr (is_list_view(TYPE::type_id)) { + size = sizes[row]; + } else { + size = offsets[row + 1] - offsets[row]; + } + } + UnsafeAppendToBitmap(is_valid); + UnsafeAppendDimensions(/*offset=*/value_builder_->length(), size); + if (is_valid) { + ARROW_RETURN_NOT_OK( + value_builder_->AppendArraySlice(array.child_data[0], offsets[row], size)); + } + } + return Status::OK(); + } + + Status ValidateOverflow(int64_t new_elements) const { + auto new_length = value_builder_->length() + new_elements; + if (ARROW_PREDICT_FALSE(new_length > maximum_elements())) { + return Status::CapacityError(type_name(), " array cannot contain more than ", + maximum_elements(), " elements, have ", new_elements); + } else { + return Status::OK(); + } + } + + ArrayBuilder* value_builder() const { return value_builder_.get(); } + + // Cannot make this a static attribute because of linking issues + static constexpr int64_t maximum_elements() { + return std::numeric_limits::max() - 1; + } + + std::shared_ptr type() const override { + return std::make_shared(value_field_->WithType(value_builder_->type())); + } + + private: + static constexpr const char* type_name() { + if constexpr (is_list_view(TYPE::type_id)) { + return "ListView"; + } else { + return "List"; + } + } + + protected: + /// \brief Append dimensions for num_values empty list slots. + /// + /// ListViewBuilder overrides this to also append the sizes. + virtual void UnsafeAppendEmptyDimensions(int64_t num_values) { + const int64_t offset = value_builder_->length(); + for (int64_t i = 0; i < num_values; ++i) { + offsets_builder_.UnsafeAppend(static_cast(offset)); + } + } + + /// \brief Append dimensions for a single list slot. + /// + /// ListViewBuilder overrides this to also append the size. + virtual void UnsafeAppendDimensions(int64_t offset, int64_t ARROW_ARG_UNUSED(size)) { + offsets_builder_.UnsafeAppend(static_cast(offset)); + } + + TypedBufferBuilder offsets_builder_; + std::shared_ptr value_builder_; + std::shared_ptr value_field_; +}; + +// ---------------------------------------------------------------------- +// ListBuilder / LargeListBuilder + +template +class BaseListBuilder : public VarLengthListLikeBuilder { + private: + using BASE = VarLengthListLikeBuilder; + + public: + using TypeClass = TYPE; + using offset_type = typename BASE::offset_type; + + using BASE::BASE; + + using BASE::Append; + + ~BaseListBuilder() override = default; + + /// \brief Start a new variable-length list slot + /// + /// This function should be called before beginning to append elements to the + /// value builder + Status Append(bool is_valid = true) { + // The value_length parameter to BASE::Append(bool, int64_t) is ignored when + // building a list array, so we can pass 0 here. + return BASE::Append(is_valid, 0); + } + + /// \brief Vector append + /// + /// If passed, valid_bytes is of equal length to values, and any zero byte + /// will be considered as a null for that slot + Status AppendValues(const offset_type* offsets, int64_t length, + const uint8_t* valid_bytes = NULLPTR) { + ARROW_RETURN_NOT_OK(this->Reserve(length)); + this->UnsafeAppendToBitmap(valid_bytes, length); + this->offsets_builder_.UnsafeAppend(offsets, length); + return Status::OK(); + } + + Status AppendValues(const offset_type* offsets, const offset_type* sizes, + int64_t length, const uint8_t* valid_bytes) final { + // Offsets are assumed to be valid, but the first length-1 sizes have to be + // consistent with the offsets to partially rule out the possibility that the + // caller is passing sizes that could work if building a list-view, but don't + // work on building a list that requires offsets to be non-decreasing. + // + // CAUTION: the last size element (`sizes[length - 1]`) is not + // validated and could be inconsistent with the offsets given in a + // subsequent call to AppendValues. +#ifndef NDEBUG + if (sizes) { + for (int64_t i = 0; i < length - 1; ++i) { + if (ARROW_PREDICT_FALSE(offsets[i] != offsets[i + 1] - sizes[i])) { + if (!valid_bytes || valid_bytes[i]) { + return Status::Invalid( + "BaseListBuilder: sizes are inconsistent with offsets provided"); + } + } + } + } +#endif + return AppendValues(offsets, length, valid_bytes); + } + + Status AppendValues(const offset_type* offsets, const offset_type* sizes, + int64_t length) { + return AppendValues(offsets, sizes, length, /*valid_bytes=*/NULLPTR); + } + + Status AppendNextOffset() { + ARROW_RETURN_NOT_OK(this->ValidateOverflow(0)); + const int64_t num_values = this->value_builder_->length(); + return this->offsets_builder_.Append(static_cast(num_values)); + } + + Status FinishInternal(std::shared_ptr* out) override { + ARROW_RETURN_NOT_OK(AppendNextOffset()); + + // Offset padding zeroed by BufferBuilder + std::shared_ptr offsets; + std::shared_ptr null_bitmap; + ARROW_RETURN_NOT_OK(this->offsets_builder_.Finish(&offsets)); + ARROW_RETURN_NOT_OK(this->null_bitmap_builder_.Finish(&null_bitmap)); + + if (this->value_builder_->length() == 0) { + // Try to make sure we get a non-null values buffer (ARROW-2744) + ARROW_RETURN_NOT_OK(this->value_builder_->Resize(0)); + } + + std::shared_ptr items; + ARROW_RETURN_NOT_OK(this->value_builder_->FinishInternal(&items)); + + *out = ArrayData::Make(this->type(), this->length_, + {std::move(null_bitmap), std::move(offsets)}, + {std::move(items)}, this->null_count_); + this->Reset(); + return Status::OK(); + } +}; + +/// \class ListBuilder +/// \brief Builder class for variable-length list array value types +/// +/// To use this class, you must append values to the child array builder and use +/// the Append function to delimit each distinct list value (once the values +/// have been appended to the child array) or use the bulk API to append +/// a sequence of offsets and null values. +/// +/// A note on types. Per arrow/type.h all types in the c++ implementation are +/// logical so even though this class always builds list array, this can +/// represent multiple different logical types. If no logical type is provided +/// at construction time, the class defaults to List where t is taken from the +/// value_builder/values that the object is constructed with. +class ARROW_EXPORT ListBuilder : public BaseListBuilder { + public: + using BaseListBuilder::BaseListBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } +}; + +/// \class LargeListBuilder +/// \brief Builder class for large variable-length list array value types +/// +/// Like ListBuilder, but to create large list arrays (with 64-bit offsets). +class ARROW_EXPORT LargeListBuilder : public BaseListBuilder { + public: + using BaseListBuilder::BaseListBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } +}; + +// ---------------------------------------------------------------------- +// ListViewBuilder / LargeListViewBuilder + +template +class BaseListViewBuilder : public VarLengthListLikeBuilder { + private: + using BASE = VarLengthListLikeBuilder; + + public: + using TypeClass = TYPE; + using offset_type = typename BASE::offset_type; + + using BASE::BASE; + + ~BaseListViewBuilder() override = default; + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(BASE::Resize(capacity)); + return sizes_builder_.Resize(capacity); + } + + void Reset() override { + BASE::Reset(); + sizes_builder_.Reset(); + } + + /// \brief Vector append + /// + /// If passed, valid_bytes is of equal length to values, and any zero byte + /// will be considered as a null for that slot + Status AppendValues(const offset_type* offsets, const offset_type* sizes, + int64_t length, const uint8_t* valid_bytes) final { + ARROW_RETURN_NOT_OK(this->Reserve(length)); + this->UnsafeAppendToBitmap(valid_bytes, length); + this->offsets_builder_.UnsafeAppend(offsets, length); + this->sizes_builder_.UnsafeAppend(sizes, length); + return Status::OK(); + } + + Status AppendValues(const offset_type* offsets, const offset_type* sizes, + int64_t length) { + return AppendValues(offsets, sizes, length, /*valid_bytes=*/NULLPTR); + } + + Status FinishInternal(std::shared_ptr* out) override { + // Offset and sizes padding zeroed by BufferBuilder + std::shared_ptr null_bitmap; + std::shared_ptr offsets; + std::shared_ptr sizes; + ARROW_RETURN_NOT_OK(this->null_bitmap_builder_.Finish(&null_bitmap)); + ARROW_RETURN_NOT_OK(this->offsets_builder_.Finish(&offsets)); + ARROW_RETURN_NOT_OK(this->sizes_builder_.Finish(&sizes)); + + if (this->value_builder_->length() == 0) { + // Try to make sure we get a non-null values buffer (ARROW-2744) + ARROW_RETURN_NOT_OK(this->value_builder_->Resize(0)); + } + + std::shared_ptr items; + ARROW_RETURN_NOT_OK(this->value_builder_->FinishInternal(&items)); + + *out = ArrayData::Make(this->type(), this->length_, + {std::move(null_bitmap), std::move(offsets), std::move(sizes)}, + {std::move(items)}, this->null_count_); + this->Reset(); + return Status::OK(); + } + + protected: + void UnsafeAppendEmptyDimensions(int64_t num_values) override { + for (int64_t i = 0; i < num_values; ++i) { + this->offsets_builder_.UnsafeAppend(0); + } + for (int64_t i = 0; i < num_values; ++i) { + this->sizes_builder_.UnsafeAppend(0); + } + } + + void UnsafeAppendDimensions(int64_t offset, int64_t size) override { + this->offsets_builder_.UnsafeAppend(static_cast(offset)); + this->sizes_builder_.UnsafeAppend(static_cast(size)); + } + + private: + TypedBufferBuilder sizes_builder_; +}; + +class ARROW_EXPORT ListViewBuilder final : public BaseListViewBuilder { + public: + using BaseListViewBuilder::BaseListViewBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } +}; + +class ARROW_EXPORT LargeListViewBuilder final + : public BaseListViewBuilder { + public: + using BaseListViewBuilder::BaseListViewBuilder; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } +}; + +// ---------------------------------------------------------------------- +// Map builder + +/// \class MapBuilder +/// \brief Builder class for arrays of variable-size maps +/// +/// To use this class, you must use the Append function to delimit each distinct +/// map before appending values to the key and item array builders, or use the +/// bulk API to append a sequence of offsets and null maps. +/// +/// Key uniqueness and ordering are not validated. +class ARROW_EXPORT MapBuilder : public ArrayBuilder { + public: + /// Use this constructor to define the built array's type explicitly. If key_builder + /// or item_builder has indeterminate type, this builder will also. + MapBuilder(MemoryPool* pool, const std::shared_ptr& key_builder, + const std::shared_ptr& item_builder, + const std::shared_ptr& type); + + /// Use this constructor to infer the built array's type. If key_builder or + /// item_builder has indeterminate type, this builder will also. + MapBuilder(MemoryPool* pool, const std::shared_ptr& key_builder, + const std::shared_ptr& item_builder, bool keys_sorted = false); + + MapBuilder(MemoryPool* pool, const std::shared_ptr& item_builder, + const std::shared_ptr& type); + + Status Resize(int64_t capacity) override; + void Reset() override; + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \brief Vector append + /// + /// If passed, valid_bytes is of equal length to values, and any zero byte + /// will be considered as a null for that slot + Status AppendValues(const int32_t* offsets, int64_t length, + const uint8_t* valid_bytes = NULLPTR); + + /// \brief Start a new variable-length map slot + /// + /// This function should be called before beginning to append elements to the + /// key and item builders + Status Append(); + + Status AppendNull() final; + + Status AppendNulls(int64_t length) final; + + Status AppendEmptyValue() final; + + Status AppendEmptyValues(int64_t length) final; + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + const auto* offsets = array.GetValues(1); + static_assert(internal::may_have_validity_bitmap(MapType::type_id)); + const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR; + for (int64_t row = offset; row < offset + length; row++) { + const bool is_valid = !validity || bit_util::GetBit(validity, array.offset + row); + if (is_valid) { + ARROW_RETURN_NOT_OK(Append()); + const int64_t slot_length = offsets[row + 1] - offsets[row]; + // Add together the inner StructArray offset to the Map/List offset + int64_t key_value_offset = array.child_data[0].offset + offsets[row]; + ARROW_RETURN_NOT_OK(key_builder_->AppendArraySlice( + array.child_data[0].child_data[0], key_value_offset, slot_length)); + ARROW_RETURN_NOT_OK(item_builder_->AppendArraySlice( + array.child_data[0].child_data[1], key_value_offset, slot_length)); + } else { + ARROW_RETURN_NOT_OK(AppendNull()); + } + } + return Status::OK(); + } + + /// \brief Get builder to append keys. + /// + /// Append a key with this builder should be followed by appending + /// an item or null value with item_builder(). + ArrayBuilder* key_builder() const { return key_builder_.get(); } + + /// \brief Get builder to append items + /// + /// Appending an item with this builder should have been preceded + /// by appending a key with key_builder(). + ArrayBuilder* item_builder() const { return item_builder_.get(); } + + /// \brief Get builder to add Map entries as struct values. + /// + /// This is used instead of key_builder()/item_builder() and allows + /// the Map to be built as a list of struct values. + ArrayBuilder* value_builder() const { return list_builder_->value_builder(); } + + std::shared_ptr type() const override { + // Key and Item builder may update types, but they don't contain the field names, + // so we need to reconstruct the type. (See ARROW-13735.) + return std::make_shared( + field(entries_name_, + struct_({field(key_name_, key_builder_->type(), false), + field(item_name_, item_builder_->type(), item_nullable_)}), + false), + keys_sorted_); + } + + Status ValidateOverflow(int64_t new_elements) { + return list_builder_->ValidateOverflow(new_elements); + } + + protected: + inline Status AdjustStructBuilderLength(); + + protected: + bool keys_sorted_ = false; + bool item_nullable_ = false; + std::string entries_name_; + std::string key_name_; + std::string item_name_; + std::shared_ptr list_builder_; + std::shared_ptr key_builder_; + std::shared_ptr item_builder_; +}; + +// ---------------------------------------------------------------------- +// FixedSizeList builder + +/// \class FixedSizeListBuilder +/// \brief Builder class for fixed-length list array value types +class ARROW_EXPORT FixedSizeListBuilder : public ArrayBuilder { + public: + using TypeClass = FixedSizeListType; + + /// Use this constructor to define the built array's type explicitly. If value_builder + /// has indeterminate type, this builder will also. + FixedSizeListBuilder(MemoryPool* pool, + const std::shared_ptr& value_builder, + int32_t list_size); + + /// Use this constructor to infer the built array's type. If value_builder has + /// indeterminate type, this builder will also. + FixedSizeListBuilder(MemoryPool* pool, + const std::shared_ptr& value_builder, + const std::shared_ptr& type); + + Status Resize(int64_t capacity) override; + void Reset() override; + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \brief Append a valid fixed length list. + /// + /// This function affects only the validity bitmap; the child values must be appended + /// using the child array builder. + Status Append(); + + /// \brief Vector append + /// + /// If passed, valid_bytes will be read and any zero byte + /// will cause the corresponding slot to be null + /// + /// This function affects only the validity bitmap; the child values must be appended + /// using the child array builder. This includes appending nulls for null lists. + /// XXX this restriction is confusing, should this method be omitted? + Status AppendValues(int64_t length, const uint8_t* valid_bytes = NULLPTR); + + /// \brief Append a null fixed length list. + /// + /// The child array builder will have the appropriate number of nulls appended + /// automatically. + Status AppendNull() final; + + /// \brief Append length null fixed length lists. + /// + /// The child array builder will have the appropriate number of nulls appended + /// automatically. + Status AppendNulls(int64_t length) final; + + Status ValidateOverflow(int64_t new_elements); + + Status AppendEmptyValue() final; + + Status AppendEmptyValues(int64_t length) final; + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length) final { + const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR; + for (int64_t row = offset; row < offset + length; row++) { + if (!validity || bit_util::GetBit(validity, array.offset + row)) { + ARROW_RETURN_NOT_OK(value_builder_->AppendArraySlice( + array.child_data[0], list_size_ * (array.offset + row), list_size_)); + ARROW_RETURN_NOT_OK(Append()); + } else { + ARROW_RETURN_NOT_OK(AppendNull()); + } + } + return Status::OK(); + } + + ArrayBuilder* value_builder() const { return value_builder_.get(); } + + std::shared_ptr type() const override { + return fixed_size_list(value_field_->WithType(value_builder_->type()), list_size_); + } + + // Cannot make this a static attribute because of linking issues + static constexpr int64_t maximum_elements() { + return std::numeric_limits::max() - 1; + } + + protected: + std::shared_ptr value_field_; + const int32_t list_size_; + std::shared_ptr value_builder_; +}; + +// ---------------------------------------------------------------------- +// Struct + +// --------------------------------------------------------------------------------- +// StructArray builder +/// Append, Resize and Reserve methods are acting on StructBuilder. +/// Please make sure all these methods of all child-builders' are consistently +/// called to maintain data-structure consistency. +class ARROW_EXPORT StructBuilder : public ArrayBuilder { + public: + /// If any of field_builders has indeterminate type, this builder will also + StructBuilder(const std::shared_ptr& type, MemoryPool* pool, + std::vector> field_builders); + + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// Null bitmap is of equal length to every child field, and any zero byte + /// will be considered as a null for that field, but users must using app- + /// end methods or advance methods of the child builders' independently to + /// insert data. + Status AppendValues(int64_t length, const uint8_t* valid_bytes) { + ARROW_RETURN_NOT_OK(Reserve(length)); + UnsafeAppendToBitmap(valid_bytes, length); + return Status::OK(); + } + + /// Append an element to the Struct. All child-builders' Append method must + /// be called independently to maintain data-structure consistency. + Status Append(bool is_valid = true) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendToBitmap(is_valid); + return Status::OK(); + } + + /// \brief Append a null value. Automatically appends an empty value to each child + /// builder. + Status AppendNull() final { + for (const auto& field : children_) { + ARROW_RETURN_NOT_OK(field->AppendEmptyValue()); + } + return Append(false); + } + + /// \brief Append multiple null values. Automatically appends empty values to each + /// child builder. + Status AppendNulls(int64_t length) final { + for (const auto& field : children_) { + ARROW_RETURN_NOT_OK(field->AppendEmptyValues(length)); + } + ARROW_RETURN_NOT_OK(Reserve(length)); + UnsafeAppendToBitmap(length, false); + return Status::OK(); + } + + Status AppendEmptyValue() final { + for (const auto& field : children_) { + ARROW_RETURN_NOT_OK(field->AppendEmptyValue()); + } + return Append(true); + } + + Status AppendEmptyValues(int64_t length) final { + for (const auto& field : children_) { + ARROW_RETURN_NOT_OK(field->AppendEmptyValues(length)); + } + ARROW_RETURN_NOT_OK(Reserve(length)); + UnsafeAppendToBitmap(length, true); + return Status::OK(); + } + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + for (int i = 0; static_cast(i) < children_.size(); i++) { + ARROW_RETURN_NOT_OK(children_[i]->AppendArraySlice(array.child_data[i], + array.offset + offset, length)); + } + const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR; + ARROW_RETURN_NOT_OK(Reserve(length)); + UnsafeAppendToBitmap(validity, array.offset + offset, length); + return Status::OK(); + } + + void Reset() override; + + ArrayBuilder* field_builder(int i) const { return children_[i].get(); } + + int num_fields() const { return static_cast(children_.size()); } + + std::shared_ptr type() const override; + + private: + std::shared_ptr type_; +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_primitive.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_primitive.h new file mode 100644 index 0000000000000000000000000000000000000000..6d79d6e9649994e99b85b233cc81ba8c1a8a1ba1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_primitive.h @@ -0,0 +1,689 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/array/builder_base.h" +#include "arrow/array/data.h" +#include "arrow/result.h" +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/float16.h" + +namespace arrow { + +class ARROW_EXPORT NullBuilder : public ArrayBuilder { + public: + explicit NullBuilder(MemoryPool* pool = default_memory_pool(), + int64_t ARROW_ARG_UNUSED(alignment) = kDefaultBufferAlignment) + : ArrayBuilder(pool) {} + + explicit NullBuilder(const std::shared_ptr& ARROW_ARG_UNUSED(type), + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : NullBuilder(pool, alignment) {} + + /// \brief Append the specified number of null elements + Status AppendNulls(int64_t length) final { + if (length < 0) return Status::Invalid("length must be positive"); + null_count_ += length; + length_ += length; + return Status::OK(); + } + + /// \brief Append a single null element + Status AppendNull() final { return AppendNulls(1); } + + Status AppendEmptyValues(int64_t length) final { return AppendNulls(length); } + + Status AppendEmptyValue() final { return AppendEmptyValues(1); } + + Status Append(std::nullptr_t) { return AppendNull(); } + + Status AppendArraySlice(const ArraySpan&, int64_t, int64_t length) override { + return AppendNulls(length); + } + + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + std::shared_ptr type() const override { return null(); } + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } +}; + +/// \addtogroup numeric-builders +/// +/// @{ + +/// Base class for all Builders that emit an Array of a scalar numerical type. +template +class NumericBuilder + : public ArrayBuilder, + public internal::ArrayBuilderExtraOps, typename T::c_type> { + public: + using TypeClass = T; + using value_type = typename T::c_type; + using ArrayType = typename TypeTraits::ArrayType; + + template + explicit NumericBuilder( + enable_if_parameter_free pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), + type_(TypeTraits::type_singleton()), + data_builder_(pool, alignment) {} + + NumericBuilder(const std::shared_ptr& type, MemoryPool* pool, + int64_t alignment = kDefaultBufferAlignment) + : ArrayBuilder(pool, alignment), type_(type), data_builder_(pool, alignment) {} + + /// Append a single scalar and increase the size if necessary. + Status Append(const value_type val) { + ARROW_RETURN_NOT_OK(ArrayBuilder::Reserve(1)); + UnsafeAppend(val); + return Status::OK(); + } + + /// Write nulls as uint8_t* (0 value indicates null) into pre-allocated memory + /// The memory at the corresponding data slot is set to 0 to prevent + /// uninitialized memory access + Status AppendNulls(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, value_type{}); // zero + UnsafeSetNull(length); + return Status::OK(); + } + + /// \brief Append a single null element + Status AppendNull() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + data_builder_.UnsafeAppend(value_type{}); // zero + UnsafeAppendToBitmap(false); + return Status::OK(); + } + + /// \brief Append a empty element + Status AppendEmptyValue() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + data_builder_.UnsafeAppend(value_type{}); // zero + UnsafeAppendToBitmap(true); + return Status::OK(); + } + + /// \brief Append several empty elements + Status AppendEmptyValues(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, value_type{}); // zero + UnsafeSetNotNull(length); + return Status::OK(); + } + + value_type GetValue(int64_t index) const { return data_builder_.data()[index]; } + + value_type* GetMutableValue(int64_t index) { + return &data_builder_.mutable_data()[index]; + } + + void Reset() override { + data_builder_.Reset(); + ArrayBuilder::Reset(); + } + + Status Resize(int64_t capacity) override { + ARROW_RETURN_NOT_OK(CheckCapacity(capacity)); + capacity = std::max(capacity, kMinBuilderCapacity); + ARROW_RETURN_NOT_OK(data_builder_.Resize(capacity)); + return ArrayBuilder::Resize(capacity); + } + + value_type operator[](int64_t index) const { return GetValue(index); } + + value_type& operator[](int64_t index) { + return reinterpret_cast(data_builder_.mutable_data())[index]; + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous C array of values + /// \param[in] length the number of values to append + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const value_type* values, int64_t length, + const uint8_t* valid_bytes = NULLPTR) { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(values, length); + // length_ is update by these + ArrayBuilder::UnsafeAppendToBitmap(valid_bytes, length); + return Status::OK(); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous C array of values + /// \param[in] length the number of values to append + /// \param[in] bitmap a validity bitmap to copy (may be null) + /// \param[in] bitmap_offset an offset into the validity bitmap + /// \return Status + Status AppendValues(const value_type* values, int64_t length, const uint8_t* bitmap, + int64_t bitmap_offset) { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(values, length); + // length_ is update by these + ArrayBuilder::UnsafeAppendToBitmap(bitmap, bitmap_offset, length); + return Status::OK(); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous C array of values + /// \param[in] length the number of values to append + /// \param[in] is_valid an std::vector indicating valid (1) or null + /// (0). Equal in length to values + /// \return Status + Status AppendValues(const value_type* values, int64_t length, + const std::vector& is_valid) { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(values, length); + // length_ is update by these + ArrayBuilder::UnsafeAppendToBitmap(is_valid); + return Status::OK(); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a std::vector of values + /// \param[in] is_valid an std::vector indicating valid (1) or null + /// (0). Equal in length to values + /// \return Status + Status AppendValues(const std::vector& values, + const std::vector& is_valid) { + if (values.empty()) { + return Status::OK(); + } + return AppendValues(values.data(), static_cast(values.size()), is_valid); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a std::vector of values + /// \return Status + Status AppendValues(const std::vector& values) { + if (values.empty()) { + return Status::OK(); + } + return AppendValues(values.data(), static_cast(values.size())); + } + + Status FinishInternal(std::shared_ptr* out) override { + ARROW_ASSIGN_OR_RAISE(auto null_bitmap, + null_bitmap_builder_.FinishWithLength(length_)); + ARROW_ASSIGN_OR_RAISE(auto data, data_builder_.FinishWithLength(length_)); + *out = ArrayData::Make(type(), length_, {null_bitmap, data}, null_count_); + capacity_ = length_ = null_count_ = 0; + return Status::OK(); + } + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values_begin InputIterator to the beginning of the values + /// \param[in] values_end InputIterator pointing to the end of the values + /// \return Status + template + Status AppendValues(ValuesIter values_begin, ValuesIter values_end) { + int64_t length = static_cast(std::distance(values_begin, values_end)); + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(values_begin, values_end); + // this updates the length_ + UnsafeSetNotNull(length); + return Status::OK(); + } + + /// \brief Append a sequence of elements in one shot, with a specified nullmap + /// \param[in] values_begin InputIterator to the beginning of the values + /// \param[in] values_end InputIterator pointing to the end of the values + /// \param[in] valid_begin InputIterator with elements indication valid(1) + /// or null(0) values. + /// \return Status + template + enable_if_t::value, Status> AppendValues( + ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) { + static_assert(!internal::is_null_pointer::value, + "Don't pass a NULLPTR directly as valid_begin, use the 2-argument " + "version instead"); + int64_t length = static_cast(std::distance(values_begin, values_end)); + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(values_begin, values_end); + null_bitmap_builder_.UnsafeAppend( + length, [&valid_begin]() -> bool { return *valid_begin++; }); + length_ = null_bitmap_builder_.length(); + null_count_ = null_bitmap_builder_.false_count(); + return Status::OK(); + } + + // Same as above, with a pointer type ValidIter + template + enable_if_t::value, Status> AppendValues( + ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) { + int64_t length = static_cast(std::distance(values_begin, values_end)); + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(values_begin, values_end); + // this updates the length_ + if (valid_begin == NULLPTR) { + UnsafeSetNotNull(length); + } else { + null_bitmap_builder_.UnsafeAppend( + length, [&valid_begin]() -> bool { return *valid_begin++; }); + length_ = null_bitmap_builder_.length(); + null_count_ = null_bitmap_builder_.false_count(); + } + + return Status::OK(); + } + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + return AppendValues(array.GetValues(1) + offset, length, + array.GetValues(0, 0), array.offset + offset); + } + + /// Append a single scalar under the assumption that the underlying Buffer is + /// large enough. + /// + /// This method does not capacity-check; make sure to call Reserve + /// beforehand. + void UnsafeAppend(const value_type val) { + ArrayBuilder::UnsafeAppendToBitmap(true); + data_builder_.UnsafeAppend(val); + } + + void UnsafeAppendNull() { + ArrayBuilder::UnsafeAppendToBitmap(false); + data_builder_.UnsafeAppend(value_type{}); // zero + } + + /// Advance builder without allocating nor writing any values + /// + /// The internal pointer is advanced by `length` values and the same number + /// of non-null entries are appended to the validity bitmap. + /// This method assumes that the `length` values were populated directly, + /// for example using `GetMutableValue`. + void UnsafeAdvance(int64_t length) { + data_builder_.UnsafeAdvance(length); + UnsafeAppendToBitmap(length, true); + } + + /// Advance builder without allocating nor writing any values + /// + /// The internal pointer is advanced by `length` values and the same number + /// of validity bits are appended to the validity bitmap. + /// This method assumes that the `length` values were populated directly, + /// for example using `GetMutableValue`. + void UnsafeAdvance(int64_t length, const uint8_t* validity, int64_t valid_bits_offset) { + data_builder_.UnsafeAdvance(length); + UnsafeAppendToBitmap(validity, valid_bits_offset, length); + } + + std::shared_ptr type() const override { return type_; } + + protected: + std::shared_ptr type_; + TypedBufferBuilder data_builder_; +}; + +// Builders + +using UInt8Builder = NumericBuilder; +using UInt16Builder = NumericBuilder; +using UInt32Builder = NumericBuilder; +using UInt64Builder = NumericBuilder; + +using Int8Builder = NumericBuilder; +using Int16Builder = NumericBuilder; +using Int32Builder = NumericBuilder; +using Int64Builder = NumericBuilder; + +using FloatBuilder = NumericBuilder; +using DoubleBuilder = NumericBuilder; + +/// @} + +/// \addtogroup temporal-builders +/// +/// @{ + +using Date32Builder = NumericBuilder; +using Date64Builder = NumericBuilder; +using Time32Builder = NumericBuilder; +using Time64Builder = NumericBuilder; +using TimestampBuilder = NumericBuilder; +using MonthIntervalBuilder = NumericBuilder; +using DurationBuilder = NumericBuilder; + +/// @} + +/// \addtogroup numeric-builders +/// +/// @{ + +class ARROW_EXPORT HalfFloatBuilder : public NumericBuilder { + public: + using BaseClass = NumericBuilder; + using Float16 = arrow::util::Float16; + + using BaseClass::Append; + using BaseClass::AppendValues; + using BaseClass::BaseClass; + using BaseClass::GetValue; + using BaseClass::UnsafeAppend; + + /// Scalar append a arrow::util::Float16 + Status Append(const Float16 val) { return Append(val.bits()); } + + /// Scalar append a arrow::util::Float16, without checking for capacity + void UnsafeAppend(const Float16 val) { UnsafeAppend(val.bits()); } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous array of arrow::util::Float16 + /// \param[in] length the number of values to append + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const Float16* values, int64_t length, + const uint8_t* valid_bytes = NULLPTR) { + return BaseClass::AppendValues(reinterpret_cast(values), length, + valid_bytes); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous array of arrow::util::Float16 + /// \param[in] length the number of values to append + /// \param[in] bitmap a validity bitmap to copy (may be null) + /// \param[in] bitmap_offset an offset into the validity bitmap + /// \return Status + Status AppendValues(const Float16* values, int64_t length, const uint8_t* bitmap, + int64_t bitmap_offset) { + return BaseClass::AppendValues(reinterpret_cast(values), length, + bitmap, bitmap_offset); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous array of arrow::util::Float16 + /// \param[in] length the number of values to append + /// \param[in] is_valid a std::vector indicating valid (1) or null + /// (0). Equal in length to values + /// \return Status + Status AppendValues(const Float16* values, int64_t length, + const std::vector& is_valid) { + return BaseClass::AppendValues(reinterpret_cast(values), length, + is_valid); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a std::vector + /// \param[in] is_valid a std::vector indicating valid (1) or null + /// (0). Equal in length to values + /// \return Status + Status AppendValues(const std::vector& values, + const std::vector& is_valid) { + return AppendValues(values.data(), static_cast(values.size()), is_valid); + } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a std::vector + /// \return Status + Status AppendValues(const std::vector& values) { + return AppendValues(values.data(), static_cast(values.size())); + } + + /// \brief Append one value many times in one shot + /// \param[in] length the number of values to append + /// \param[in] value a arrow::util::Float16 + Status AppendValues(int64_t length, Float16 value) { + RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, value.bits()); + ArrayBuilder::UnsafeSetNotNull(length); + return Status::OK(); + } + + /// \brief Get the value at a certain index + /// \param[in] index the zero-based index + /// @tparam T arrow::util::Float16 or value_type (uint16_t) + template + T GetValue(int64_t index) const { + static_assert(std::is_same_v || + std::is_same_v); + if constexpr (std::is_same_v) { + return BaseClass::GetValue(index); + } else { + return Float16::FromBits(BaseClass::GetValue(index)); + } + } +}; + +/// @} + +class ARROW_EXPORT BooleanBuilder + : public ArrayBuilder, + public internal::ArrayBuilderExtraOps { + public: + using TypeClass = BooleanType; + using value_type = bool; + + explicit BooleanBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + BooleanBuilder(const std::shared_ptr& type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment); + + /// Write nulls as uint8_t* (0 value indicates null) into pre-allocated memory + Status AppendNulls(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, false); + UnsafeSetNull(length); + return Status::OK(); + } + + Status AppendNull() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppendNull(); + return Status::OK(); + } + + Status AppendEmptyValue() final { + ARROW_RETURN_NOT_OK(Reserve(1)); + data_builder_.UnsafeAppend(false); + UnsafeSetNotNull(1); + return Status::OK(); + } + + Status AppendEmptyValues(int64_t length) final { + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend(length, false); + UnsafeSetNotNull(length); + return Status::OK(); + } + + /// Scalar append + Status Append(const bool val) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(val); + return Status::OK(); + } + + Status Append(const uint8_t val) { return Append(val != 0); } + + /// Scalar append, without checking for capacity + void UnsafeAppend(const bool val) { + data_builder_.UnsafeAppend(val); + UnsafeAppendToBitmap(true); + } + + void UnsafeAppendNull() { + data_builder_.UnsafeAppend(false); + UnsafeAppendToBitmap(false); + } + + void UnsafeAppend(const uint8_t val) { UnsafeAppend(val != 0); } + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous array of bytes (non-zero is 1) + /// \param[in] length the number of values to append + /// \param[in] valid_bytes an optional sequence of bytes where non-zero + /// indicates a valid (non-null) value + /// \return Status + Status AppendValues(const uint8_t* values, int64_t length, + const uint8_t* valid_bytes = NULLPTR); + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a bitmap of values + /// \param[in] length the number of values to append + /// \param[in] validity a validity bitmap to copy (may be null) + /// \param[in] offset an offset into the values and validity bitmaps + /// \return Status + Status AppendValues(const uint8_t* values, int64_t length, const uint8_t* validity, + int64_t offset); + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a contiguous C array of values + /// \param[in] length the number of values to append + /// \param[in] is_valid an std::vector indicating valid (1) or null + /// (0). Equal in length to values + /// \return Status + Status AppendValues(const uint8_t* values, int64_t length, + const std::vector& is_valid); + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a std::vector of bytes + /// \param[in] is_valid an std::vector indicating valid (1) or null + /// (0). Equal in length to values + /// \return Status + Status AppendValues(const std::vector& values, + const std::vector& is_valid); + + /// \brief Append a sequence of elements in one shot + /// \param[in] values a std::vector of bytes + /// \return Status + Status AppendValues(const std::vector& values); + + /// \brief Append a sequence of elements in one shot + /// \param[in] values an std::vector indicating true (1) or false + /// \param[in] is_valid an std::vector indicating valid (1) or null + /// (0). Equal in length to values + /// \return Status + Status AppendValues(const std::vector& values, const std::vector& is_valid); + + /// \brief Append a sequence of elements in one shot + /// \param[in] values an std::vector indicating true (1) or false + /// \return Status + Status AppendValues(const std::vector& values); + + /// \brief Append a sequence of elements in one shot + /// \param[in] values_begin InputIterator to the beginning of the values + /// \param[in] values_end InputIterator pointing to the end of the values + /// or null(0) values + /// \return Status + template + Status AppendValues(ValuesIter values_begin, ValuesIter values_end) { + int64_t length = static_cast(std::distance(values_begin, values_end)); + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend( + length, [&values_begin]() -> bool { return *values_begin++; }); + // this updates length_ + UnsafeSetNotNull(length); + return Status::OK(); + } + + /// \brief Append a sequence of elements in one shot, with a specified nullmap + /// \param[in] values_begin InputIterator to the beginning of the values + /// \param[in] values_end InputIterator pointing to the end of the values + /// \param[in] valid_begin InputIterator with elements indication valid(1) + /// or null(0) values + /// \return Status + template + enable_if_t::value, Status> AppendValues( + ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) { + static_assert(!internal::is_null_pointer::value, + "Don't pass a NULLPTR directly as valid_begin, use the 2-argument " + "version instead"); + int64_t length = static_cast(std::distance(values_begin, values_end)); + ARROW_RETURN_NOT_OK(Reserve(length)); + + data_builder_.UnsafeAppend( + length, [&values_begin]() -> bool { return *values_begin++; }); + null_bitmap_builder_.UnsafeAppend( + length, [&valid_begin]() -> bool { return *valid_begin++; }); + length_ = null_bitmap_builder_.length(); + null_count_ = null_bitmap_builder_.false_count(); + return Status::OK(); + } + + // Same as above, for a pointer type ValidIter + template + enable_if_t::value, Status> AppendValues( + ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) { + int64_t length = static_cast(std::distance(values_begin, values_end)); + ARROW_RETURN_NOT_OK(Reserve(length)); + data_builder_.UnsafeAppend( + length, [&values_begin]() -> bool { return *values_begin++; }); + + if (valid_begin == NULLPTR) { + UnsafeSetNotNull(length); + } else { + null_bitmap_builder_.UnsafeAppend( + length, [&valid_begin]() -> bool { return *valid_begin++; }); + } + length_ = null_bitmap_builder_.length(); + null_count_ = null_bitmap_builder_.false_count(); + return Status::OK(); + } + + Status AppendValues(int64_t length, bool value); + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override { + return AppendValues(array.GetValues(1, 0), length, + array.GetValues(0, 0), array.offset + offset); + } + + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + void Reset() override; + Status Resize(int64_t capacity) override; + + std::shared_ptr type() const override { return boolean(); } + + protected: + TypedBufferBuilder data_builder_; +}; + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_run_end.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_run_end.h new file mode 100644 index 0000000000000000000000000000000000000000..ac92efbd0dbe6b470b8275219e75b41aa3f7ab3a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_run_end.h @@ -0,0 +1,303 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/array.h" +#include "arrow/array/builder_base.h" + +namespace arrow { + +/// \addtogroup run-end-encoded-builders +/// +/// @{ + +namespace internal { + +/// \brief An ArrayBuilder that deduplicates repeated values as they are +/// appended to the inner-ArrayBuilder and reports the length of the current run +/// of identical values. +/// +/// The following sequence of calls +/// +/// Append(2) +/// Append(2) +/// Append(2) +/// Append(7) +/// Append(7) +/// Append(2) +/// FinishInternal() +/// +/// will cause the inner-builder to receive only 3 Append calls +/// +/// Append(2) +/// Append(7) +/// Append(2) +/// FinishInternal() +/// +/// Note that values returned by length(), null_count() and capacity() are +/// related to the compressed array built by the inner-ArrayBuilder. +class RunCompressorBuilder : public ArrayBuilder { + public: + RunCompressorBuilder(MemoryPool* pool, std::shared_ptr inner_builder, + std::shared_ptr type); + + ~RunCompressorBuilder() override; + + ARROW_DISALLOW_COPY_AND_ASSIGN(RunCompressorBuilder); + + /// \brief Called right before a run is being closed + /// + /// Subclasses can override this function to perform an additional action when + /// a run is closed (i.e. run-length is known and value is appended to the + /// inner builder). + /// + /// \param value can be NULLPTR if closing a run of NULLs + /// \param length the greater than 0 length of the value run being closed + virtual Status WillCloseRun(const std::shared_ptr& value, + int64_t length) { + return Status::OK(); + } + + /// \brief Called right before a run of empty values is being closed + /// + /// Subclasses can override this function to perform an additional action when + /// a run of empty values is appended (i.e. run-length is known and a single + /// empty value is appended to the inner builder). + /// + /// \param length the greater than 0 length of the value run being closed + virtual Status WillCloseRunOfEmptyValues(int64_t length) { return Status::OK(); } + + /// \brief Allocate enough memory for a given number of array elements. + /// + /// NOTE: Conservatively resizing a run-length compressed array for a given + /// number of logical elements is not possible, since the physical length will + /// vary depending on the values to be appended in the future. But we can + /// pessimistically assume that each run will contain a single value and + /// allocate that number of runs. + Status Resize(int64_t capacity) override { return ResizePhysical(capacity); } + + /// \brief Allocate enough memory for a given number of runs. + /// + /// Like Resize on non-encoded builders, it does not account for variable size + /// data. + Status ResizePhysical(int64_t capacity); + + Status ReservePhysical(int64_t additional_capacity) { + return Reserve(additional_capacity); + } + + void Reset() override; + + Status AppendNull() final { return AppendNulls(1); } + Status AppendNulls(int64_t length) override; + + Status AppendEmptyValue() final { return AppendEmptyValues(1); } + Status AppendEmptyValues(int64_t length) override; + + Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override; + Status AppendScalars(const ScalarVector& scalars) override; + + // AppendArraySlice() is not implemented. + + /// \brief Append a slice of an array containing values from already + /// compressed runs. + /// + /// NOTE: WillCloseRun() is not called as the length of each run cannot be + /// determined at this point. Caller should ensure that !has_open_run() by + /// calling FinishCurrentRun() before calling this. + /// + /// Pre-condition: !has_open_run() + Status AppendRunCompressedArraySlice(const ArraySpan& array, int64_t offset, + int64_t length); + + /// \brief Forces the closing of the current run if one is currently open. + /// + /// This can be called when one wants to ensure the current run will not be + /// extended. This may cause identical values to appear close to each other in + /// the underlying array (i.e. two runs that could be a single run) if more + /// values are appended after this is called. + /// + /// Finish() and FinishInternal() call this automatically. + virtual Status FinishCurrentRun(); + + Status FinishInternal(std::shared_ptr* out) override; + + ArrayBuilder& inner_builder() const { return *inner_builder_; } + + std::shared_ptr type() const override { return inner_builder_->type(); } + + bool has_open_run() const { return current_run_length_ > 0; } + int64_t open_run_length() const { return current_run_length_; } + + private: + inline void UpdateDimensions() { + capacity_ = inner_builder_->capacity(); + length_ = inner_builder_->length(); + null_count_ = inner_builder_->null_count(); + } + + private: + std::shared_ptr inner_builder_; + std::shared_ptr current_value_ = NULLPTR; + int64_t current_run_length_ = 0; +}; + +} // namespace internal + +// ---------------------------------------------------------------------- +// RunEndEncoded builder + +/// \brief Run-end encoded array builder. +/// +/// NOTE: the value returned by and capacity() is related to the +/// compressed array (physical) and not the decoded array (logical) that is +/// run-end encoded. null_count() always returns 0. length(), on the other hand, +/// returns the logical length of the run-end encoded array. +class ARROW_EXPORT RunEndEncodedBuilder : public ArrayBuilder { + private: + // An internal::RunCompressorBuilder that produces a run-end in the + // RunEndEncodedBuilder every time a value-run is closed. + class ValueRunBuilder : public internal::RunCompressorBuilder { + public: + ValueRunBuilder(MemoryPool* pool, const std::shared_ptr& value_builder, + const std::shared_ptr& value_type, + RunEndEncodedBuilder& ree_builder); + + ~ValueRunBuilder() override = default; + + Status WillCloseRun(const std::shared_ptr&, int64_t length) override { + return ree_builder_.CloseRun(length); + } + + Status WillCloseRunOfEmptyValues(int64_t length) override { + return ree_builder_.CloseRun(length); + } + + private: + RunEndEncodedBuilder& ree_builder_; + }; + + public: + RunEndEncodedBuilder(MemoryPool* pool, + const std::shared_ptr& run_end_builder, + const std::shared_ptr& value_builder, + std::shared_ptr type); + + /// \brief Allocate enough memory for a given number of array elements. + /// + /// NOTE: Conservatively resizing an REE for a given number of logical + /// elements is not possible, since the physical length will vary depending on + /// the values to be appended in the future. But we can pessimistically assume + /// that each run will contain a single value and allocate that number of + /// runs. + Status Resize(int64_t capacity) override { return ResizePhysical(capacity); } + + /// \brief Allocate enough memory for a given number of runs. + Status ResizePhysical(int64_t capacity); + + /// \brief Ensure that there is enough space allocated to append the indicated + /// number of run without any further reallocation. Overallocation is + /// used in order to minimize the impact of incremental ReservePhysical() calls. + /// Note that additional_capacity is relative to the current number of elements + /// rather than to the current capacity, so calls to Reserve() which are not + /// interspersed with addition of new elements may not increase the capacity. + /// + /// \param[in] additional_capacity the number of additional runs + /// \return Status + Status ReservePhysical(int64_t additional_capacity) { + return Reserve(additional_capacity); + } + + void Reset() override; + + Status AppendNull() final { return AppendNulls(1); } + Status AppendNulls(int64_t length) override; + + Status AppendEmptyValue() final { return AppendEmptyValues(1); } + Status AppendEmptyValues(int64_t length) override; + Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override; + Status AppendScalars(const ScalarVector& scalars) override; + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override; + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \brief Forces the closing of the current run if one is currently open. + /// + /// This can be called when one wants to ensure the current run will not be + /// extended. This may cause identical values to appear close to each other in + /// the values array (i.e. two runs that could be a single run) if more + /// values are appended after this is called. + Status FinishCurrentRun(); + + std::shared_ptr type() const override; + + private: + /// \brief Update physical capacity and logical length + /// + /// \param committed_logical_length number of logical values that have been + /// committed to the values array + /// \param open_run_length number of logical values in the currently open run if any + inline void UpdateDimensions(int64_t committed_logical_length, + int64_t open_run_length) { + capacity_ = run_end_builder().capacity(); + length_ = committed_logical_length + open_run_length; + committed_logical_length_ = committed_logical_length; + } + + // Pre-condition: !value_run_builder_.has_open_run() + template + Status DoAppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length); + + template + Status DoAppendRunEnd(int64_t run_end); + + /// \brief Cast run_end to the appropriate type and appends it to the run_ends + /// array. + Status AppendRunEnd(int64_t run_end); + + /// \brief Close a run by appending a value to the run_ends array and updating + /// length_ to reflect the new run. + /// + /// Pre-condition: run_length > 0. + [[nodiscard]] Status CloseRun(int64_t run_length); + + ArrayBuilder& run_end_builder(); + ArrayBuilder& value_builder(); + + private: + std::shared_ptr type_; + ValueRunBuilder* value_run_builder_; + // The length not counting the current open run in the value_run_builder_ + int64_t committed_logical_length_ = 0; +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_time.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_time.h new file mode 100644 index 0000000000000000000000000000000000000000..b471e9621cd4b125fd44e8f2f4239c7f720ac95d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_time.h @@ -0,0 +1,64 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Contains declarations of time related Arrow builder types. + +#pragma once + +#include + +#include "arrow/array/builder_base.h" +#include "arrow/array/builder_primitive.h" + +namespace arrow { + +/// \addtogroup temporal-builders +/// +/// @{ + +class ARROW_EXPORT DayTimeIntervalBuilder : public NumericBuilder { + public: + using DayMilliseconds = DayTimeIntervalType::DayMilliseconds; + + explicit DayTimeIntervalBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : DayTimeIntervalBuilder(day_time_interval(), pool, alignment) {} + + explicit DayTimeIntervalBuilder(std::shared_ptr type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : NumericBuilder(type, pool, alignment) {} +}; + +class ARROW_EXPORT MonthDayNanoIntervalBuilder + : public NumericBuilder { + public: + using MonthDayNanos = MonthDayNanoIntervalType::MonthDayNanos; + + explicit MonthDayNanoIntervalBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : MonthDayNanoIntervalBuilder(month_day_nano_interval(), pool, alignment) {} + + explicit MonthDayNanoIntervalBuilder(std::shared_ptr type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : NumericBuilder(type, pool, alignment) {} +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_union.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_union.h new file mode 100644 index 0000000000000000000000000000000000000000..718ef4c32cebef1d30e4f7c036a7ab8f4b333e4a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/builder_union.h @@ -0,0 +1,254 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/array/array_nested.h" +#include "arrow/array/builder_base.h" +#include "arrow/array/data.h" +#include "arrow/buffer_builder.h" +#include "arrow/memory_pool.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \addtogroup nested-builders +/// +/// @{ + +/// \brief Base class for union array builds. +/// +/// Note that while we subclass ArrayBuilder, as union types do not have a +/// validity bitmap, the bitmap builder member of ArrayBuilder is not used. +class ARROW_EXPORT BasicUnionBuilder : public ArrayBuilder { + public: + Status FinishInternal(std::shared_ptr* out) override; + + /// \cond FALSE + using ArrayBuilder::Finish; + /// \endcond + + Status Finish(std::shared_ptr* out) { return FinishTyped(out); } + + /// \brief Make a new child builder available to the UnionArray + /// + /// \param[in] new_child the child builder + /// \param[in] field_name the name of the field in the union array type + /// if type inference is used + /// \return child index, which is the "type" argument that needs + /// to be passed to the "Append" method to add a new element to + /// the union array. + int8_t AppendChild(const std::shared_ptr& new_child, + const std::string& field_name = ""); + + std::shared_ptr type() const override; + + int64_t length() const override { return types_builder_.length(); } + + protected: + BasicUnionBuilder(MemoryPool* pool, int64_t alignment, + const std::vector>& children, + const std::shared_ptr& type); + + int8_t NextTypeId(); + + std::vector> child_fields_; + std::vector type_codes_; + UnionMode::type mode_; + + std::vector type_id_to_children_; + std::vector type_id_to_child_id_; + // for all type_id < dense_type_id_, type_id_to_children_[type_id] != nullptr + int8_t dense_type_id_ = 0; + TypedBufferBuilder types_builder_; +}; + +/// \class DenseUnionBuilder +/// +/// This API is EXPERIMENTAL. +class ARROW_EXPORT DenseUnionBuilder : public BasicUnionBuilder { + public: + /// Use this constructor to initialize the UnionBuilder with no child builders, + /// allowing type to be inferred. You will need to call AppendChild for each of the + /// children builders you want to use. + explicit DenseUnionBuilder(MemoryPool* pool, + int64_t alignment = kDefaultBufferAlignment) + : BasicUnionBuilder(pool, alignment, {}, dense_union(FieldVector{})), + offsets_builder_(pool, alignment) {} + + /// Use this constructor to specify the type explicitly. + /// You can still add child builders to the union after using this constructor + DenseUnionBuilder(MemoryPool* pool, + const std::vector>& children, + const std::shared_ptr& type, + int64_t alignment = kDefaultBufferAlignment) + : BasicUnionBuilder(pool, alignment, children, type), + offsets_builder_(pool, alignment) {} + + Status AppendNull() final { + const int8_t first_child_code = type_codes_[0]; + ArrayBuilder* child_builder = type_id_to_children_[first_child_code]; + ARROW_RETURN_NOT_OK(types_builder_.Append(first_child_code)); + ARROW_RETURN_NOT_OK( + offsets_builder_.Append(static_cast(child_builder->length()))); + // Append a null arbitrarily to the first child + return child_builder->AppendNull(); + } + + Status AppendNulls(int64_t length) final { + const int8_t first_child_code = type_codes_[0]; + ArrayBuilder* child_builder = type_id_to_children_[first_child_code]; + ARROW_RETURN_NOT_OK(types_builder_.Append(length, first_child_code)); + ARROW_RETURN_NOT_OK( + offsets_builder_.Append(length, static_cast(child_builder->length()))); + // Append just a single null to the first child + return child_builder->AppendNull(); + } + + Status AppendEmptyValue() final { + const int8_t first_child_code = type_codes_[0]; + ArrayBuilder* child_builder = type_id_to_children_[first_child_code]; + ARROW_RETURN_NOT_OK(types_builder_.Append(first_child_code)); + ARROW_RETURN_NOT_OK( + offsets_builder_.Append(static_cast(child_builder->length()))); + // Append an empty value arbitrarily to the first child + return child_builder->AppendEmptyValue(); + } + + Status AppendEmptyValues(int64_t length) final { + const int8_t first_child_code = type_codes_[0]; + ArrayBuilder* child_builder = type_id_to_children_[first_child_code]; + ARROW_RETURN_NOT_OK(types_builder_.Append(length, first_child_code)); + ARROW_RETURN_NOT_OK( + offsets_builder_.Append(length, static_cast(child_builder->length()))); + // Append just a single empty value to the first child + return child_builder->AppendEmptyValue(); + } + + /// \brief Append an element to the UnionArray. This must be followed + /// by an append to the appropriate child builder. + /// + /// \param[in] next_type type_id of the child to which the next value will be appended. + /// + /// The corresponding child builder must be appended to independently after this method + /// is called. + Status Append(int8_t next_type) { + ARROW_RETURN_NOT_OK(types_builder_.Append(next_type)); + if (type_id_to_children_[next_type]->length() == kListMaximumElements) { + return Status::CapacityError( + "a dense UnionArray cannot contain more than 2^31 - 1 elements from a single " + "child"); + } + auto offset = static_cast(type_id_to_children_[next_type]->length()); + return offsets_builder_.Append(offset); + } + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override; + + Status FinishInternal(std::shared_ptr* out) override; + + private: + TypedBufferBuilder offsets_builder_; +}; + +/// \class SparseUnionBuilder +/// +/// This API is EXPERIMENTAL. +class ARROW_EXPORT SparseUnionBuilder : public BasicUnionBuilder { + public: + /// Use this constructor to initialize the UnionBuilder with no child builders, + /// allowing type to be inferred. You will need to call AppendChild for each of the + /// children builders you want to use. + explicit SparseUnionBuilder(MemoryPool* pool, + int64_t alignment = kDefaultBufferAlignment) + : BasicUnionBuilder(pool, alignment, {}, sparse_union(FieldVector{})) {} + + /// Use this constructor to specify the type explicitly. + /// You can still add child builders to the union after using this constructor + SparseUnionBuilder(MemoryPool* pool, + const std::vector>& children, + const std::shared_ptr& type, + int64_t alignment = kDefaultBufferAlignment) + : BasicUnionBuilder(pool, alignment, children, type) {} + + /// \brief Append a null value. + /// + /// A null is appended to the first child, empty values to the other children. + Status AppendNull() final { + const auto first_child_code = type_codes_[0]; + ARROW_RETURN_NOT_OK(types_builder_.Append(first_child_code)); + ARROW_RETURN_NOT_OK(type_id_to_children_[first_child_code]->AppendNull()); + for (int i = 1; i < static_cast(type_codes_.size()); ++i) { + ARROW_RETURN_NOT_OK(type_id_to_children_[type_codes_[i]]->AppendEmptyValue()); + } + return Status::OK(); + } + + /// \brief Append multiple null values. + /// + /// Nulls are appended to the first child, empty values to the other children. + Status AppendNulls(int64_t length) final { + const auto first_child_code = type_codes_[0]; + ARROW_RETURN_NOT_OK(types_builder_.Append(length, first_child_code)); + ARROW_RETURN_NOT_OK(type_id_to_children_[first_child_code]->AppendNulls(length)); + for (int i = 1; i < static_cast(type_codes_.size()); ++i) { + ARROW_RETURN_NOT_OK( + type_id_to_children_[type_codes_[i]]->AppendEmptyValues(length)); + } + return Status::OK(); + } + + Status AppendEmptyValue() final { + ARROW_RETURN_NOT_OK(types_builder_.Append(type_codes_[0])); + for (int8_t code : type_codes_) { + ARROW_RETURN_NOT_OK(type_id_to_children_[code]->AppendEmptyValue()); + } + return Status::OK(); + } + + Status AppendEmptyValues(int64_t length) final { + ARROW_RETURN_NOT_OK(types_builder_.Append(length, type_codes_[0])); + for (int8_t code : type_codes_) { + ARROW_RETURN_NOT_OK(type_id_to_children_[code]->AppendEmptyValues(length)); + } + return Status::OK(); + } + + /// \brief Append an element to the UnionArray. This must be followed + /// by an append to the appropriate child builder. + /// + /// \param[in] next_type type_id of the child to which the next value will be appended. + /// + /// The corresponding child builder must be appended to independently after this method + /// is called, and all other child builders must have null or empty value appended. + Status Append(int8_t next_type) { return types_builder_.Append(next_type); } + + Status AppendArraySlice(const ArraySpan& array, int64_t offset, + int64_t length) override; +}; + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/concatenate.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/concatenate.h new file mode 100644 index 0000000000000000000000000000000000000000..aada5624d63a3052edddf0182799c474bee0c528 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/concatenate.h @@ -0,0 +1,53 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace internal { + +/// \brief Concatenate arrays +/// +/// \param[in] arrays a vector of arrays to be concatenated +/// \param[in] pool memory to store the result will be allocated from this memory pool +/// \param[out] out_suggested_cast if a non-OK Result is returned, the function might set +/// out_suggested_cast to a cast suggestion that would allow concatenating the arrays +/// without overflow of offsets (e.g. string to large_string) +/// +/// \return the concatenated array +ARROW_EXPORT +Result> Concatenate(const ArrayVector& arrays, MemoryPool* pool, + std::shared_ptr* out_suggested_cast); + +} // namespace internal + +/// \brief Concatenate arrays +/// +/// \param[in] arrays a vector of arrays to be concatenated +/// \param[in] pool memory to store the result will be allocated from this memory pool +/// \return the concatenated array +ARROW_EXPORT +Result> Concatenate(const ArrayVector& arrays, + MemoryPool* pool = default_memory_pool()); + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/data.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/data.h new file mode 100644 index 0000000000000000000000000000000000000000..c6636df9bb3025de78b00b1f5b4265783c05e148 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/data.h @@ -0,0 +1,750 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include // IWYU pragma: export +#include +#include +#include +#include +#include + +#include "arrow/array/statistics.h" +#include "arrow/buffer.h" +#include "arrow/result.h" +#include "arrow/type.h" +#include "arrow/type_fwd.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/macros.h" +#include "arrow/util/span.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +namespace internal { +// ---------------------------------------------------------------------- +// Null handling for types without a validity bitmap and the dictionary type + +ARROW_EXPORT bool IsNullSparseUnion(const ArrayData& data, int64_t i); +ARROW_EXPORT bool IsNullDenseUnion(const ArrayData& data, int64_t i); +ARROW_EXPORT bool IsNullRunEndEncoded(const ArrayData& data, int64_t i); + +ARROW_EXPORT bool UnionMayHaveLogicalNulls(const ArrayData& data); +ARROW_EXPORT bool RunEndEncodedMayHaveLogicalNulls(const ArrayData& data); +ARROW_EXPORT bool DictionaryMayHaveLogicalNulls(const ArrayData& data); + +} // namespace internal + +// When slicing, we do not know the null count of the sliced range without +// doing some computation. To avoid doing this eagerly, we set the null count +// to -1 (any negative number will do). When Array::null_count is called the +// first time, the null count will be computed. See ARROW-33 +constexpr int64_t kUnknownNullCount = -1; + +// ---------------------------------------------------------------------- +// Generic array data container + +/// \class ArrayData +/// \brief Mutable container for generic Arrow array data +/// +/// This data structure is a self-contained representation of the memory and +/// metadata inside an Arrow array data structure (called vectors in Java). The +/// Array class and its concrete subclasses provide strongly-typed accessors +/// with support for the visitor pattern and other affordances. +/// +/// This class is designed for easy internal data manipulation, analytical data +/// processing, and data transport to and from IPC messages. +/// +/// This class is also useful in an analytics setting where memory may be +/// efficiently reused. For example, computing the Abs of a numeric array +/// should return null iff the input is null: therefore, an Abs function can +/// reuse the validity bitmap (a Buffer) of its input as the validity bitmap +/// of its output. +/// +/// This class is meant mostly for immutable data access. Any mutable access +/// (either to ArrayData members or to the contents of its Buffers) should take +/// into account the fact that ArrayData instances are typically wrapped in a +/// shared_ptr and can therefore have multiple owners at any given time. +/// Therefore, mutable access is discouraged except when initially populating +/// the ArrayData. +struct ARROW_EXPORT ArrayData { + ArrayData() = default; + + ArrayData(std::shared_ptr type, int64_t length, + int64_t null_count = kUnknownNullCount, int64_t offset = 0) + : type(std::move(type)), length(length), null_count(null_count), offset(offset) {} + + ArrayData(std::shared_ptr type, int64_t length, + std::vector> buffers, + int64_t null_count = kUnknownNullCount, int64_t offset = 0) + : ArrayData(std::move(type), length, null_count, offset) { + this->buffers = std::move(buffers); +#ifndef NDEBUG + // in debug mode, call the `device_type` function to trigger + // the DCHECKs that validate all the buffers are on the same device + ARROW_UNUSED(this->device_type()); +#endif + } + + ArrayData(std::shared_ptr type, int64_t length, + std::vector> buffers, + std::vector> child_data, + int64_t null_count = kUnknownNullCount, int64_t offset = 0) + : ArrayData(std::move(type), length, null_count, offset) { + this->buffers = std::move(buffers); + this->child_data = std::move(child_data); +#ifndef NDEBUG + // in debug mode, call the `device_type` function to trigger + // the DCHECKs that validate all the buffers (including children) + // are on the same device + ARROW_UNUSED(this->device_type()); +#endif + } + + static std::shared_ptr Make(std::shared_ptr type, int64_t length, + std::vector> buffers, + int64_t null_count = kUnknownNullCount, + int64_t offset = 0); + + static std::shared_ptr Make( + std::shared_ptr type, int64_t length, + std::vector> buffers, + std::vector> child_data, + int64_t null_count = kUnknownNullCount, int64_t offset = 0); + + static std::shared_ptr Make( + std::shared_ptr type, int64_t length, + std::vector> buffers, + std::vector> child_data, + std::shared_ptr dictionary, int64_t null_count = kUnknownNullCount, + int64_t offset = 0); + + static std::shared_ptr Make(std::shared_ptr type, int64_t length, + int64_t null_count = kUnknownNullCount, + int64_t offset = 0); + + // Move constructor + ArrayData(ArrayData&& other) noexcept + : type(std::move(other.type)), + length(other.length), + null_count(other.null_count.load()), + offset(other.offset), + buffers(std::move(other.buffers)), + child_data(std::move(other.child_data)), + dictionary(std::move(other.dictionary)), + statistics(std::move(other.statistics)) {} + + // Copy constructor + ArrayData(const ArrayData& other) noexcept + : type(other.type), + length(other.length), + null_count(other.null_count.load()), + offset(other.offset), + buffers(other.buffers), + child_data(other.child_data), + dictionary(other.dictionary), + statistics(other.statistics) {} + + // Move assignment + ArrayData& operator=(ArrayData&& other) { + type = std::move(other.type); + length = other.length; + SetNullCount(other.null_count); + offset = other.offset; + buffers = std::move(other.buffers); + child_data = std::move(other.child_data); + dictionary = std::move(other.dictionary); + statistics = std::move(other.statistics); + return *this; + } + + // Copy assignment + ArrayData& operator=(const ArrayData& other) { + type = other.type; + length = other.length; + SetNullCount(other.null_count); + offset = other.offset; + buffers = other.buffers; + child_data = other.child_data; + dictionary = other.dictionary; + statistics = other.statistics; + return *this; + } + + /// \brief Return a shallow copy of this ArrayData + std::shared_ptr Copy() const { return std::make_shared(*this); } + + /// \brief Deep copy this ArrayData to destination memory manager + /// + /// Returns a new ArrayData object with buffers and all child buffers + /// copied to the destination memory manager. This includes dictionaries + /// if applicable. + Result> CopyTo( + const std::shared_ptr& to) const; + + /// \brief View or copy this ArrayData to destination memory manager + /// + /// Tries to view the buffer contents on the given memory manager's device + /// if possible (to avoid a copy) but falls back to copying if a no-copy view + /// isn't supported. + Result> ViewOrCopyTo( + const std::shared_ptr& to) const; + + /// \brief Return the null-ness of a given array element + /// + /// Calling `IsNull(i)` is the same as `!IsValid(i)`. + bool IsNull(int64_t i) const { return !IsValid(i); } + + /// \brief Return the validity of a given array element + /// + /// For most data types, this will simply query the validity bitmap. + /// For union and run-end-encoded arrays, the underlying child data is + /// queried instead. + /// For dictionary arrays, this reflects the validity of the dictionary + /// index, but the corresponding dictionary value might still be null. + /// For null arrays, this always returns false. + bool IsValid(int64_t i) const { + if (buffers[0] != NULLPTR) { + return bit_util::GetBit(buffers[0]->data(), i + offset); + } + const auto type = this->type->id(); + if (type == Type::SPARSE_UNION) { + return !internal::IsNullSparseUnion(*this, i); + } + if (type == Type::DENSE_UNION) { + return !internal::IsNullDenseUnion(*this, i); + } + if (type == Type::RUN_END_ENCODED) { + return !internal::IsNullRunEndEncoded(*this, i); + } + return null_count.load() != length; + } + + /// \brief Access a buffer's data as a typed C pointer + /// + /// \param i the buffer index + /// \param absolute_offset the offset into the buffer + /// + /// If `absolute_offset` is non-zero, the type `T` must match the + /// layout of buffer number `i` for the array's data type; otherwise + /// offset computation would be incorrect. + /// + /// If the given buffer is bit-packed (such as a validity bitmap, or + /// the data buffer of a boolean array), then `absolute_offset` must be + /// zero for correct results, and any bit offset must be applied manually + /// by the caller. + template + inline const T* GetValues(int i, int64_t absolute_offset) const { + if (buffers[i]) { + return reinterpret_cast(buffers[i]->data()) + absolute_offset; + } else { + return NULLPTR; + } + } + + /// \brief Access a buffer's data as a typed C pointer + /// + /// \param i the buffer index + /// + /// This method uses the array's offset to index into buffer number `i`. + /// + /// Calling this method on a bit-packed buffer (such as a validity bitmap, or + /// the data buffer of a boolean array) will lead to incorrect results. + /// You should instead call `GetValues(i, 0)` and apply the bit offset manually. + template + inline const T* GetValues(int i) const { + return GetValues(i, offset); + } + + /// \brief Access a buffer's data as a typed C pointer + /// + /// \param i the buffer index + /// \param absolute_offset the offset into the buffer + /// + /// Like `GetValues(i, absolute_offset)`, but returns nullptr if the given buffer + /// is not a CPU buffer. + template + inline const T* GetValuesSafe(int i, int64_t absolute_offset) const { + if (buffers[i] && buffers[i]->is_cpu()) { + return reinterpret_cast(buffers[i]->data()) + absolute_offset; + } else { + return NULLPTR; + } + } + + /// \brief Access a buffer's data as a typed C pointer + /// + /// \param i the buffer index + /// + /// Like `GetValues(i)`, but returns nullptr if the given buffer is not a CPU buffer. + template + inline const T* GetValuesSafe(int i) const { + return GetValuesSafe(i, offset); + } + + /// \brief Access a buffer's data as a mutable typed C pointer + /// + /// \param i the buffer index + /// \param absolute_offset the offset into the buffer + /// + /// Like `GetValues(i, absolute_offset)`, but allows mutating buffer contents. + /// This should only be used when initially populating the ArrayData, before + /// it is attached to a Array instance. + template + inline T* GetMutableValues(int i, int64_t absolute_offset) { + if (buffers[i]) { + return reinterpret_cast(buffers[i]->mutable_data()) + absolute_offset; + } else { + return NULLPTR; + } + } + + /// \brief Access a buffer's data as a mutable typed C pointer + /// + /// \param i the buffer index + /// + /// Like `GetValues(i)`, but allows mutating buffer contents. + /// This should only be used when initially populating the ArrayData, before + /// it is attached to a Array instance. + template + inline T* GetMutableValues(int i) { + return GetMutableValues(i, offset); + } + + /// \brief Construct a zero-copy slice of the data with the given offset and length + /// + /// This method applies the given slice to this ArrayData, taking into account + /// its existing offset and length. + /// If the given `length` is too large, the slice length is clamped so as not + /// to go past the offset end. + /// If the given `often` is too large, or if either `offset` or `length` is negative, + /// behavior is undefined. + /// + /// The associated ArrayStatistics is always discarded in a sliced + /// ArrayData, even if the slice is trivially equal to the original ArrayData. + /// If you want to reuse the statistics from the original ArrayData, you must + /// explicitly reattach them. + std::shared_ptr Slice(int64_t offset, int64_t length) const; + + /// \brief Construct a zero-copy slice of the data with the given offset and length + /// + /// Like `Slice(offset, length)`, but returns an error if the requested slice + /// falls out of bounds. + /// Unlike Slice, `length` isn't clamped to the available buffer size. + Result> SliceSafe(int64_t offset, int64_t length) const; + + /// \brief Set the cached physical null count + /// + /// \param v the number of nulls in the ArrayData + /// + /// This should only be used when initially populating the ArrayData, if + /// it possible to compute the null count without visiting the entire validity + /// bitmap. In most cases, relying on `GetNullCount` is sufficient. + void SetNullCount(int64_t v) { null_count.store(v); } + + /// \brief Return the physical null count + /// + /// This method returns the number of array elements for which `IsValid` would + /// return false. + /// + /// A cached value is returned if already available, otherwise it is first + /// computed and stored. + /// How it is is computed depends on the data type, see `IsValid` for details. + /// + /// Note that this method is typically much faster than calling `IsValid` + /// for all elements. Therefore, it helps avoid per-element validity bitmap + /// lookups in the common cases where the array contains zero or only nulls. + int64_t GetNullCount() const; + + /// \brief Return true if the array may have nulls in its validity bitmap + /// + /// This method returns true if the data has a validity bitmap, and the physical + /// null count is either known to be non-zero or not yet known. + /// + /// Unlike `MayHaveLogicalNulls`, this does not check for the presence of nulls + /// in child data for data types such as unions and run-end encoded types. + /// + /// \see HasValidityBitmap + /// \see MayHaveLogicalNulls + bool MayHaveNulls() const { + // If an ArrayData is slightly malformed it may have kUnknownNullCount set + // but no buffer + return null_count.load() != 0 && buffers[0] != NULLPTR; + } + + /// \brief Return true if the array has a validity bitmap + bool HasValidityBitmap() const { return buffers[0] != NULLPTR; } + + /// \brief Return true if the array may have logical nulls + /// + /// Unlike `MayHaveNulls`, this method checks for null child values + /// for types without a validity bitmap, such as unions and run-end encoded + /// types, and for null dictionary values for dictionary types. + /// + /// This implies that `MayHaveLogicalNulls` may return true for arrays that + /// don't have a top-level validity bitmap. It is therefore necessary + /// to call `HasValidityBitmap` before accessing a top-level validity bitmap. + /// + /// Code that previously used MayHaveNulls and then dealt with the validity + /// bitmap directly can be fixed to handle all types correctly without + /// performance degradation when handling most types by adopting + /// HasValidityBitmap and MayHaveLogicalNulls. + /// + /// Before: + /// + /// uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR; + /// for (int64_t i = 0; i < array.length; ++i) { + /// if (validity && !bit_util::GetBit(validity, i)) { + /// continue; // skip a NULL + /// } + /// ... + /// } + /// + /// After: + /// + /// bool all_valid = !array.MayHaveLogicalNulls(); + /// uint8_t* validity = array.HasValidityBitmap() ? array.buffers[0].data : NULLPTR; + /// for (int64_t i = 0; i < array.length; ++i) { + /// bool is_valid = all_valid || + /// (validity && bit_util::GetBit(validity, i)) || + /// array.IsValid(i); + /// if (!is_valid) { + /// continue; // skip a NULL + /// } + /// ... + /// } + bool MayHaveLogicalNulls() const { + if (buffers[0] != NULLPTR) { + return null_count.load() != 0; + } + const auto t = type->id(); + if (t == Type::SPARSE_UNION || t == Type::DENSE_UNION) { + return internal::UnionMayHaveLogicalNulls(*this); + } + if (t == Type::RUN_END_ENCODED) { + return internal::RunEndEncodedMayHaveLogicalNulls(*this); + } + if (t == Type::DICTIONARY) { + return internal::DictionaryMayHaveLogicalNulls(*this); + } + return null_count.load() != 0; + } + + /// \brief Compute the logical null count for arrays of all types + /// + /// If the array has a validity bitmap, this function behaves the same as + /// GetNullCount. For arrays that have no validity bitmap but whose values + /// may be logically null (such as union arrays and run-end encoded arrays), + /// this function recomputes the null count every time it is called. + /// + /// \see GetNullCount + int64_t ComputeLogicalNullCount() const; + + /// \brief Return the device_type of the underlying buffers and children + /// + /// If there are no buffers in this ArrayData object, it just returns + /// DeviceAllocationType::kCPU as a default. We also assume that all buffers + /// should be allocated on the same device type and perform DCHECKs to confirm + /// this in debug mode. + /// + /// \return DeviceAllocationType + DeviceAllocationType device_type() const; + + std::shared_ptr type; + int64_t length = 0; + mutable std::atomic null_count{0}; + // The logical start point into the physical buffers (in values, not bytes). + // Note that, for child data, this must be *added* to the child data's own offset. + int64_t offset = 0; + std::vector> buffers; + std::vector> child_data; + + // The dictionary for this Array, if any. Only used for dictionary type + std::shared_ptr dictionary; + + // The statistics for this Array. + std::shared_ptr statistics; +}; + +/// \brief A non-owning Buffer reference +struct ARROW_EXPORT BufferSpan { + // It is the user of this class's responsibility to ensure that + // buffers that were const originally are not written to + // accidentally. + uint8_t* data = NULLPTR; + int64_t size = 0; + // Pointer back to buffer that owns this memory + const std::shared_ptr* owner = NULLPTR; + + template + const T* data_as() const { + return reinterpret_cast(data); + } + template + T* mutable_data_as() { + return reinterpret_cast(data); + } +}; + +/// \brief EXPERIMENTAL: A non-owning array data container +/// +/// Unlike ArrayData, this class doesn't own its referenced data type nor data buffers. +/// It is cheaply copyable and can therefore be suitable for use cases where +/// shared_ptr overhead is not acceptable. However, care should be taken to +/// keep alive the referenced objects and memory while the ArraySpan object is in use. +/// For this reason, this should not be exposed in most public APIs (apart from +/// compute kernel interfaces). +struct ARROW_EXPORT ArraySpan { + const DataType* type = NULLPTR; + int64_t length = 0; + mutable int64_t null_count = kUnknownNullCount; + int64_t offset = 0; + BufferSpan buffers[3]; + + ArraySpan() = default; + + explicit ArraySpan(const DataType* type, int64_t length) : type(type), length(length) {} + + ArraySpan(const ArrayData& data) { // NOLINT implicit conversion + SetMembers(data); + } + explicit ArraySpan(const Scalar& data) { FillFromScalar(data); } + + /// If dictionary-encoded, put dictionary in the first entry + std::vector child_data; + + /// \brief Populate ArraySpan to look like an array of length 1 pointing at + /// the data members of a Scalar value + void FillFromScalar(const Scalar& value); + + void SetMembers(const ArrayData& data); + + void SetBuffer(int index, const std::shared_ptr& buffer) { + this->buffers[index].data = const_cast(buffer->data()); + this->buffers[index].size = buffer->size(); + this->buffers[index].owner = &buffer; + } + + const ArraySpan& dictionary() const { return child_data[0]; } + + /// \brief Return the number of buffers (out of 3) that are used to + /// constitute this array + int num_buffers() const; + + // Access a buffer's data as a typed C pointer + template + inline T* GetValues(int i, int64_t absolute_offset) { + return reinterpret_cast(buffers[i].data) + absolute_offset; + } + + template + inline T* GetValues(int i) { + return GetValues(i, this->offset); + } + + // Access a buffer's data as a typed C pointer + template + inline const T* GetValues(int i, int64_t absolute_offset) const { + return reinterpret_cast(buffers[i].data) + absolute_offset; + } + + template + inline const T* GetValues(int i) const { + return GetValues(i, this->offset); + } + + /// \brief Access a buffer's data as a span + /// + /// \param i The buffer index + /// \param length The required length (in number of typed values) of the requested span + /// \pre i > 0 + /// \pre length <= the length of the buffer (in number of values) that's expected for + /// this array type + /// \return A span of the requested length + template + util::span GetSpan(int i, int64_t length) const { + const int64_t buffer_length = buffers[i].size / static_cast(sizeof(T)); + assert(i > 0 && length + offset <= buffer_length); + ARROW_UNUSED(buffer_length); + return util::span(buffers[i].data_as() + this->offset, length); + } + + /// \brief Access a buffer's data as a span + /// + /// \param i The buffer index + /// \param length The required length (in number of typed values) of the requested span + /// \pre i > 0 + /// \pre length <= the length of the buffer (in number of values) that's expected for + /// this array type + /// \return A span of the requested length + template + util::span GetSpan(int i, int64_t length) { + const int64_t buffer_length = buffers[i].size / static_cast(sizeof(T)); + assert(i > 0 && length + offset <= buffer_length); + ARROW_UNUSED(buffer_length); + return util::span(buffers[i].mutable_data_as() + this->offset, length); + } + + inline bool IsNull(int64_t i) const { return !IsValid(i); } + + inline bool IsValid(int64_t i) const { + if (this->buffers[0].data != NULLPTR) { + return bit_util::GetBit(this->buffers[0].data, i + this->offset); + } else { + const auto type = this->type->id(); + if (type == Type::SPARSE_UNION) { + return !IsNullSparseUnion(i); + } + if (type == Type::DENSE_UNION) { + return !IsNullDenseUnion(i); + } + if (type == Type::RUN_END_ENCODED) { + return !IsNullRunEndEncoded(i); + } + return this->null_count != this->length; + } + } + + std::shared_ptr ToArrayData() const; + + std::shared_ptr ToArray() const; + + std::shared_ptr GetBuffer(int index) const { + const BufferSpan& buf = this->buffers[index]; + if (buf.owner) { + return *buf.owner; + } else if (buf.data != NULLPTR) { + // Buffer points to some memory without an owning buffer + return std::make_shared(buf.data, buf.size); + } else { + return NULLPTR; + } + } + + void SetSlice(int64_t offset, int64_t length) { + this->offset = offset; + this->length = length; + if (this->type->id() == Type::NA) { + this->null_count = this->length; + } else if (buffers[0].data != NULLPTR) { + this->null_count = kUnknownNullCount; + } else { + this->null_count = 0; + } + } + + /// \brief Return physical null count, or compute and set it if it's not known + int64_t GetNullCount() const; + + /// \brief Return true if the array has a validity bitmap and the physical null + /// count is known to be non-zero or not yet known + /// + /// Note that this is not the same as MayHaveLogicalNulls, which also checks + /// for the presence of nulls in child data for types like unions and run-end + /// encoded types. + /// + /// \see HasValidityBitmap + /// \see MayHaveLogicalNulls + bool MayHaveNulls() const { + // If an ArrayData is slightly malformed it may have kUnknownNullCount set + // but no buffer + return null_count != 0 && buffers[0].data != NULLPTR; + } + + /// \brief Return true if the array has a validity bitmap + bool HasValidityBitmap() const { return buffers[0].data != NULLPTR; } + + /// \brief Return true if the validity bitmap may have 0's in it, or if the + /// child arrays (in the case of types without a validity bitmap) may have + /// nulls, or if the dictionary of dictionay array may have nulls. + /// + /// \see ArrayData::MayHaveLogicalNulls + bool MayHaveLogicalNulls() const { + if (buffers[0].data != NULLPTR) { + return null_count != 0; + } + const auto t = type->id(); + if (t == Type::SPARSE_UNION || t == Type::DENSE_UNION) { + return UnionMayHaveLogicalNulls(); + } + if (t == Type::RUN_END_ENCODED) { + return RunEndEncodedMayHaveLogicalNulls(); + } + if (t == Type::DICTIONARY) { + return DictionaryMayHaveLogicalNulls(); + } + return null_count != 0; + } + + /// \brief Compute the logical null count for arrays of all types including + /// those that do not have a validity bitmap like union and run-end encoded + /// arrays + /// + /// If the array has a validity bitmap, this function behaves the same as + /// GetNullCount. For types that have no validity bitmap, this function will + /// recompute the logical null count every time it is called. + /// + /// \see GetNullCount + int64_t ComputeLogicalNullCount() const; + + /// Some DataTypes (StringView, BinaryView) may have an arbitrary number of variadic + /// buffers. Since ArraySpan only has 3 buffers, we pack the variadic buffers into + /// buffers[2]; IE buffers[2].data points to the first shared_ptr of the + /// variadic set and buffers[2].size is the number of variadic buffers times + /// sizeof(shared_ptr). + /// + /// \see HasVariadicBuffers + util::span> GetVariadicBuffers() const; + bool HasVariadicBuffers() const; + + private: + ARROW_FRIEND_EXPORT friend bool internal::IsNullRunEndEncoded(const ArrayData& data, + int64_t i); + + bool IsNullSparseUnion(int64_t i) const; + bool IsNullDenseUnion(int64_t i) const; + + /// \brief Return true if the value at logical index i is null + /// + /// This function uses binary-search, so it has a O(log N) cost. + /// Iterating over the whole array and calling IsNull is O(N log N), so + /// for better performance it is recommended to use a + /// ree_util::RunEndEncodedArraySpan to iterate run by run instead. + bool IsNullRunEndEncoded(int64_t i) const; + + bool UnionMayHaveLogicalNulls() const; + bool RunEndEncodedMayHaveLogicalNulls() const; + bool DictionaryMayHaveLogicalNulls() const; +}; + +namespace internal { + +void FillZeroLengthArray(const DataType* type, ArraySpan* span); + +/// Construct a zero-copy view of this ArrayData with the given type. +/// +/// This method checks if the types are layout-compatible. +/// Nested types are traversed in depth-first order. Data buffers must have +/// the same item sizes, even though the logical types may be different. +/// An error is returned if the types are not layout-compatible. +ARROW_EXPORT +Result> GetArrayView(const std::shared_ptr& data, + const std::shared_ptr& type); + +} // namespace internal +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/diff.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/diff.h new file mode 100644 index 0000000000000000000000000000000000000000..a405164b333f3b21a17e8414ef59a8a628c28579 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/diff.h @@ -0,0 +1,76 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/array/array_nested.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \brief Compare two arrays, returning an edit script which expresses the difference +/// between them +/// +/// An edit script is an array of struct(insert: bool, run_length: int64_t). +/// Each element of "insert" determines whether an element was inserted into (true) +/// or deleted from (false) base. Each insertion or deletion is followed by a run of +/// elements which are unchanged from base to target; the length of this run is stored +/// in "run_length". (Note that the edit script begins and ends with a run of shared +/// elements but both fields of the struct must have the same length. To accommodate this +/// the first element of "insert" should be ignored.) +/// +/// For example for base "hlloo" and target "hello", the edit script would be +/// [ +/// {"insert": false, "run_length": 1}, // leading run of length 1 ("h") +/// {"insert": true, "run_length": 3}, // insert("e") then a run of length 3 ("llo") +/// {"insert": false, "run_length": 0} // delete("o") then an empty run +/// ] +/// +/// Diffing arrays containing nulls is not currently supported. +/// +/// \param[in] base baseline for comparison +/// \param[in] target an array of identical type to base whose elements differ from base's +/// \param[in] pool memory to store the result will be allocated from this memory pool +/// \return an edit script array which can be applied to base to produce target +ARROW_EXPORT +Result> Diff(const Array& base, const Array& target, + MemoryPool* pool = default_memory_pool()); + +/// \brief visitor interface for easy traversal of an edit script +/// +/// visitor will be called for each hunk of insertions and deletions. +ARROW_EXPORT Status VisitEditScript( + const Array& edits, + const std::function& visitor); + +/// \brief return a function which will format an edit script in unified +/// diff format to os, given base and target arrays of type +ARROW_EXPORT Result< + std::function> +MakeUnifiedDiffFormatter(const DataType& type, std::ostream* os); + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/statistics.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/statistics.h new file mode 100644 index 0000000000000000000000000000000000000000..ae78dca0b0c6b19b4ad4bfc8deb9962260afb466 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/statistics.h @@ -0,0 +1,175 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/compare.h" +#include "arrow/type.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \class ArrayStatistics +/// \brief Statistics for an Array +/// +/// Apache Arrow format doesn't have statistics but data source such +/// as Apache Parquet may have statistics. Statistics associated with +/// data source can be read unified API via this class. +struct ARROW_EXPORT ArrayStatistics { + /// \brief The type for maximum and minimum values. If the target + /// value exists, one of them is used. `std::nullopt` is used + /// otherwise. + using ValueType = std::variant; + using NumericType = std::variant; + using CountType = NumericType; + using SizeType = NumericType; + + static const std::shared_ptr& ValueToArrowType( + const std::optional& value, + const std::shared_ptr& array_type) { + if (!value.has_value()) { + return null(); + } + + struct Visitor { + const std::shared_ptr& array_type; + + const std::shared_ptr& operator()(const bool&) { return boolean(); } + const std::shared_ptr& operator()(const int64_t&) { return int64(); } + const std::shared_ptr& operator()(const uint64_t&) { return uint64(); } + const std::shared_ptr& operator()(const double&) { return float64(); } + const std::shared_ptr& operator()(const std::string&) { + switch (array_type->id()) { + case Type::STRING: + case Type::BINARY: + case Type::FIXED_SIZE_BINARY: + case Type::LARGE_STRING: + case Type::LARGE_BINARY: + case Type::BINARY_VIEW: + case Type::STRING_VIEW: + return array_type; + default: + return utf8(); + } + } + } visitor{array_type}; + return std::visit(visitor, value.value()); + } + + /// \brief The number of rows, may not be set + /// Note: when set to `int64_t`, it represents `exact_row_count`, + /// and when set to `double`, it represents `approximate_row_count`. + /// Note: this value is not used by \ref arrow::RecordBatch::MakeStatisticsArray. + std::optional row_count = std::nullopt; + + /// \brief The number of null values, may not be set + /// Note: when set to `int64_t`, it represents `exact_null_count`, + /// and when set to `double`, it represents `approximate_null_count`. + std::optional null_count = std::nullopt; + + /// \brief The number of distinct values, may not be set + /// Note: when set to `int64_t`, it represents `exact_distinct_count`, + /// and when set to `double`, it represents `approximate_distinct_count`. + std::optional distinct_count = std::nullopt; + + /// \brief The maximum length in bytes of the rows in an array; may not be set + /// Note: when the type is `int64_t`, it represents `max_byte_width_exact`, + /// and when the type is `double`, it represents `max_byte_width_approximate`. + std::optional max_byte_width = std::nullopt; + + /// \brief The average size in bytes of a row in an array, may not be set. + std::optional average_byte_width = std::nullopt; + + /// \brief Whether the average size in bytes is exact or not. + bool is_average_byte_width_exact = false; + + /// \brief The minimum value, may not be set + std::optional min = std::nullopt; + + /// \brief Compute Arrow type of the minimum value. + /// + /// If \ref ValueType is `std::string`, `array_type` may be + /// used. If `array_type` is a binary-like type such as \ref + /// arrow::binary and \ref arrow::large_utf8, `array_type` is + /// returned. \ref arrow::utf8 is returned otherwise. + /// + /// If \ref ValueType isn't `std::string`, `array_type` isn't used. + /// + /// \param array_type The Arrow type of the associated array. + /// + /// \return \ref arrow::null if the minimum value is `std::nullopt`, + /// Arrow type based on \ref ValueType of the \ref min + /// otherwise. + const std::shared_ptr& MinArrowType( + const std::shared_ptr& array_type) { + return ValueToArrowType(min, array_type); + } + + /// \brief Whether the minimum value is exact or not + bool is_min_exact = false; + + /// \brief The maximum value, may not be set + std::optional max = std::nullopt; + + /// \brief Compute Arrow type of the maximum value. + /// + /// If \ref ValueType is `std::string`, `array_type` may be + /// used. If `array_type` is a binary-like type such as \ref + /// arrow::binary and \ref arrow::large_utf8, `array_type` is + /// returned. \ref arrow::utf8 is returned otherwise. + /// + /// If \ref ValueType isn't `std::string`, `array_type` isn't used. + /// + /// \param array_type The Arrow type of the associated array. + /// + /// \return \ref arrow::null if the maximum value is `std::nullopt`, + /// Arrow type based on \ref ValueType of the \ref max + /// otherwise. + const std::shared_ptr& MaxArrowType( + const std::shared_ptr& array_type) { + return ValueToArrowType(max, array_type); + } + + /// \brief Whether the maximum value is exact or not + bool is_max_exact = false; + + /// \brief Check two \ref arrow::ArrayStatistics for equality + /// + /// \param other The \ref arrow::ArrayStatistics instance to compare against. + /// + /// \param equal_options Options used to compare double values for equality. + /// + /// \return True if the two \ref arrow::ArrayStatistics instances are equal; otherwise, + /// false. + bool Equals(const ArrayStatistics& other, + const EqualOptions& equal_options = EqualOptions::Defaults()) const { + return ArrayStatisticsEquals(*this, other, equal_options); + } + + /// \brief Check two statistics for equality + bool operator==(const ArrayStatistics& other) const { return Equals(other); } + + /// \brief Check two statistics for not equality + bool operator!=(const ArrayStatistics& other) const { return !Equals(other); } +}; + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/util.h new file mode 100644 index 0000000000000000000000000000000000000000..fd8e75ddb86405c523a8083f559dab0e72364e24 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/util.h @@ -0,0 +1,96 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/array/data.h" +#include "arrow/compare.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +/// \defgroup array-factories Array factory functions +/// +/// @{ + +/// \brief Create a strongly-typed Array instance from generic ArrayData +/// \param[in] data the array contents +/// \return the resulting Array instance +ARROW_EXPORT +std::shared_ptr MakeArray(const std::shared_ptr& data); + +/// \brief Create a strongly-typed Array instance with all elements null +/// \param[in] type the array type +/// \param[in] length the array length +/// \param[in] pool the memory pool to allocate memory from +ARROW_EXPORT +Result> MakeArrayOfNull(const std::shared_ptr& type, + int64_t length, + MemoryPool* pool = default_memory_pool()); + +/// \brief Create an Array instance whose slots are the given scalar +/// \param[in] scalar the value with which to fill the array +/// \param[in] length the array length +/// \param[in] pool the memory pool to allocate memory from +ARROW_EXPORT +Result> MakeArrayFromScalar( + const Scalar& scalar, int64_t length, MemoryPool* pool = default_memory_pool()); + +/// \brief Create an empty Array of a given type +/// +/// The output Array will be of the given type. +/// +/// \param[in] type the data type of the empty Array +/// \param[in] pool the memory pool to allocate memory from +/// \return the resulting Array +ARROW_EXPORT +Result> MakeEmptyArray(std::shared_ptr type, + MemoryPool* pool = default_memory_pool()); + +/// @} + +namespace internal { + +/// \brief Swap endian of each element in a generic ArrayData +/// +/// As dictionaries are often shared between different arrays, dictionaries +/// are not swapped by this function and should be handled separately. +/// +/// \param[in] data the array contents +/// \param[in] pool the memory pool to allocate memory from +/// \return the resulting ArrayData whose elements were swapped +ARROW_EXPORT +Result> SwapEndianArrayData( + const std::shared_ptr& data, MemoryPool* pool = default_memory_pool()); + +/// Given a number of ArrayVectors, treat each ArrayVector as the +/// chunks of a chunked array. Then rechunk each ArrayVector such that +/// all ArrayVectors are chunked identically. It is mandatory that +/// all ArrayVectors contain the same total number of elements. +ARROW_EXPORT +std::vector RechunkArraysConsistently(const std::vector&); + +} // namespace internal +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/validate.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/validate.h new file mode 100644 index 0000000000000000000000000000000000000000..3ebfa0a51edce21ca585862b1dbb074b6cf8d9c8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/array/validate.h @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace internal { + +// Internal functions implementing Array::Validate() and friends. + +// O(1) array metadata validation + +ARROW_EXPORT +Status ValidateArray(const Array& array); + +ARROW_EXPORT +Status ValidateArray(const ArrayData& data); + +// O(N) array data validation. +// Note that, starting from 7.0.0, "full" routines also validate metadata. +// Before, ValidateArray() needed to be called before ValidateArrayFull() +// to ensure metadata correctness, otherwise invalid memory accesses +// may occur. + +ARROW_EXPORT +Status ValidateArrayFull(const Array& array); + +ARROW_EXPORT +Status ValidateArrayFull(const ArrayData& data); + +ARROW_EXPORT +Status ValidateUTF8(const Array& array); + +ARROW_EXPORT +Status ValidateUTF8(const ArrayData& data); + +} // namespace internal +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/buffer.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..ce909a3ea182f4d1d8fb294512ccc74e55bf0030 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/buffer.h @@ -0,0 +1,587 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/device.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/span.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +// ---------------------------------------------------------------------- +// Buffer classes + +/// \class Buffer +/// \brief Object containing a pointer to a piece of contiguous memory with a +/// particular size. +/// +/// Buffers have two related notions of length: size and capacity. Size is +/// the number of bytes that might have valid data. Capacity is the number +/// of bytes that were allocated for the buffer in total. +/// +/// The Buffer base class does not own its memory, but subclasses often do. +/// +/// The following invariant is always true: Size <= Capacity +class ARROW_EXPORT Buffer { + public: + ARROW_DISALLOW_COPY_AND_ASSIGN(Buffer); + + /// \brief Construct from buffer and size without copying memory + /// + /// \param[in] data a memory buffer + /// \param[in] size buffer size + /// + /// \note The passed memory must be kept alive through some other means + Buffer(const uint8_t* data, int64_t size) + : is_mutable_(false), + is_cpu_(true), + data_(data), + size_(size), + capacity_(size), + device_type_(DeviceAllocationType::kCPU) { + SetMemoryManager(default_cpu_memory_manager()); + } + + Buffer(const uint8_t* data, int64_t size, std::shared_ptr mm, + std::shared_ptr parent = NULLPTR, + std::optional device_type_override = std::nullopt) + : is_mutable_(false), + data_(data), + size_(size), + capacity_(size), + parent_(std::move(parent)) { + // SetMemoryManager will also set device_type_ + SetMemoryManager(std::move(mm)); + // If a device type is specified, use that instead. Example of when this can be + // useful: the CudaMemoryManager can set device_type_ to kCUDA, but you can specify + // device_type_override=kCUDA_HOST as the device type to override it. + if (device_type_override != std::nullopt) { + device_type_ = *device_type_override; + } + } + + Buffer(uintptr_t address, int64_t size, std::shared_ptr mm, + std::shared_ptr parent = NULLPTR) + : Buffer(reinterpret_cast(address), size, std::move(mm), + std::move(parent)) {} + + /// \brief Construct from string_view without copying memory + /// + /// \param[in] data a string_view object + /// + /// \note The memory viewed by data must not be deallocated in the lifetime of the + /// Buffer; temporary rvalue strings must be stored in an lvalue somewhere + explicit Buffer(std::string_view data) + : Buffer(reinterpret_cast(data.data()), + static_cast(data.size())) {} + + virtual ~Buffer() = default; + + /// An offset into data that is owned by another buffer, but we want to be + /// able to retain a valid pointer to it even after other shared_ptr's to the + /// parent buffer have been destroyed + /// + /// This method makes no assertions about alignment or padding of the buffer but + /// in general we expected buffers to be aligned and padded to 64 bytes. In the future + /// we might add utility methods to help determine if a buffer satisfies this contract. + Buffer(std::shared_ptr parent, const int64_t offset, const int64_t size) + : Buffer(parent->data_ + offset, size) { + parent_ = std::move(parent); + SetMemoryManager(parent_->memory_manager_); + } + + uint8_t operator[](std::size_t i) const { return data_[i]; } + + /// \brief Construct a new std::string with a hexadecimal representation of the buffer. + /// \return std::string + std::string ToHexString(); + + /// Return true if both buffers are the same size and contain the same bytes + /// up to the number of compared bytes + bool Equals(const Buffer& other, int64_t nbytes) const; + + /// Return true if both buffers are the same size and contain the same bytes + bool Equals(const Buffer& other) const; + + /// Copy a section of the buffer into a new Buffer. + Result> CopySlice( + const int64_t start, const int64_t nbytes, + MemoryPool* pool = default_memory_pool()) const; + + /// Zero bytes in padding, i.e. bytes between size_ and capacity_. + void ZeroPadding() { +#ifndef NDEBUG + CheckMutable(); +#endif + // A zero-capacity buffer can have a null data pointer + if (capacity_ != 0) { + memset(mutable_data() + size_, 0, static_cast(capacity_ - size_)); + } + } + + /// \brief Construct an immutable buffer that takes ownership of the contents + /// of an std::string (without copying it). + /// + /// \param[in] data a string to own + /// \return a new Buffer instance + static std::shared_ptr FromString(std::string data); + + /// \brief Construct an immutable buffer that takes ownership of the contents + /// of an std::vector (without copying it). Only vectors of TrivialType objects + /// (integers, floating point numbers, ...) can be wrapped by this function. + /// + /// \param[in] vec a vector to own + /// \return a new Buffer instance + template + static std::shared_ptr FromVector(std::vector vec) { + static_assert(std::is_trivial_v, + "Buffer::FromVector can only wrap vectors of trivial objects"); + + if (vec.empty()) { + return std::shared_ptr{new Buffer()}; + } + + auto* data = reinterpret_cast(vec.data()); + auto size_in_bytes = static_cast(vec.size() * sizeof(T)); + return std::shared_ptr{ + new Buffer{data, size_in_bytes}, + // Keep the vector's buffer alive inside the shared_ptr's destructor until after + // we have deleted the Buffer. Note we can't use this trick in FromString since + // std::string's data is inline for short strings so moving invalidates pointers + // into the string's buffer. + [vec = std::move(vec)](Buffer* buffer) { delete buffer; }}; + } + + /// \brief Create buffer referencing typed memory with some length without + /// copying + /// \param[in] data the typed memory as C array + /// \param[in] length the number of values in the array + /// \return a new shared_ptr + template + static std::shared_ptr Wrap(const T* data, SizeType length) { + return std::make_shared(reinterpret_cast(data), + static_cast(sizeof(T) * length)); + } + + /// \brief Create buffer referencing std::vector with some length without + /// copying + /// \param[in] data the vector to be referenced. If this vector is changed, + /// the buffer may become invalid + /// \return a new shared_ptr + template + static std::shared_ptr Wrap(const std::vector& data) { + return std::make_shared(reinterpret_cast(data.data()), + static_cast(sizeof(T) * data.size())); + } + + /// \brief Copy buffer contents into a new std::string + /// \return std::string + /// \note Can throw std::bad_alloc if buffer is large + std::string ToString() const; + + /// \brief View buffer contents as a std::string_view + /// \return std::string_view + explicit operator std::string_view() const { + return {reinterpret_cast(data_), static_cast(size_)}; + } + + /// \brief Return a pointer to the buffer's data + /// + /// The buffer has to be a CPU buffer (`is_cpu()` is true). + /// Otherwise, an assertion may be thrown or a null pointer may be returned. + /// + /// To get the buffer's data address regardless of its device, call `address()`. + const uint8_t* data() const { +#ifndef NDEBUG + CheckCPU(); +#endif + return ARROW_PREDICT_TRUE(is_cpu_) ? data_ : NULLPTR; + } + + /// \brief Return a pointer to the buffer's data cast to a specific type + /// + /// The buffer has to be a CPU buffer (`is_cpu()` is true). + /// Otherwise, an assertion may be thrown or a null pointer may be returned. + template + const T* data_as() const { + return reinterpret_cast(data()); + } + + /// \brief Return the buffer's data as a span + template + util::span span_as() const { + return util::span(data_as(), static_cast(size() / sizeof(T))); + } + + /// \brief Return a writable pointer to the buffer's data + /// + /// The buffer has to be a mutable CPU buffer (`is_cpu()` and `is_mutable()` + /// are true). Otherwise, an assertion may be thrown or a null pointer may + /// be returned. + /// + /// To get the buffer's mutable data address regardless of its device, call + /// `mutable_address()`. + uint8_t* mutable_data() { +#ifndef NDEBUG + CheckCPU(); + CheckMutable(); +#endif + return ARROW_PREDICT_TRUE(is_cpu_ && is_mutable_) ? const_cast(data_) + : NULLPTR; + } + + /// \brief Return a writable pointer to the buffer's data cast to a specific type + /// + /// The buffer has to be a mutable CPU buffer (`is_cpu()` and `is_mutable()` + /// are true). Otherwise, an assertion may be thrown or a null pointer may + /// be returned. + template + T* mutable_data_as() { + return reinterpret_cast(mutable_data()); + } + + /// \brief Return the buffer's mutable data as a span + template + util::span mutable_span_as() { + return util::span(mutable_data_as(), static_cast(size() / sizeof(T))); + } + + /// \brief Return the device address of the buffer's data + uintptr_t address() const { return reinterpret_cast(data_); } + + /// \brief Return a writable device address to the buffer's data + /// + /// The buffer has to be a mutable buffer (`is_mutable()` is true). + /// Otherwise, an assertion may be thrown or 0 may be returned. + uintptr_t mutable_address() const { +#ifndef NDEBUG + CheckMutable(); +#endif + return ARROW_PREDICT_TRUE(is_mutable_) ? reinterpret_cast(data_) : 0; + } + + /// \brief Return the buffer's size in bytes + int64_t size() const { return size_; } + + /// \brief Return the buffer's capacity (number of allocated bytes) + int64_t capacity() const { return capacity_; } + + /// \brief Whether the buffer is directly CPU-accessible + /// + /// If this function returns true, you can read directly from the buffer's + /// `data()` pointer. Otherwise, you'll have to `View()` or `Copy()` it. + bool is_cpu() const { return is_cpu_; } + + /// \brief Whether the buffer is mutable + /// + /// If this function returns true, you are allowed to modify buffer contents + /// using the pointer returned by `mutable_data()` or `mutable_address()`. + bool is_mutable() const { return is_mutable_; } + + const std::shared_ptr& device() const { return memory_manager_->device(); } + + const std::shared_ptr& memory_manager() const { return memory_manager_; } + + DeviceAllocationType device_type() const { return device_type_; } + + std::shared_ptr parent() const { return parent_; } + + /// \brief Get a RandomAccessFile for reading a buffer + /// + /// The returned file object reads from this buffer's underlying memory. + static Result> GetReader(std::shared_ptr); + + /// \brief Get a OutputStream for writing to a buffer + /// + /// The buffer must be mutable. The returned stream object writes into the buffer's + /// underlying memory (but it won't resize it). + static Result> GetWriter(std::shared_ptr); + + /// \brief Copy buffer + /// + /// The buffer contents will be copied into a new buffer allocated by the + /// given MemoryManager. This function supports cross-device copies. + static Result> Copy(std::shared_ptr source, + const std::shared_ptr& to); + + /// \brief Copy a non-owned buffer + /// + /// This is useful for cases where the source memory area is externally managed + /// (its lifetime not tied to the source Buffer), otherwise please use Copy(). + static Result> CopyNonOwned( + const Buffer& source, const std::shared_ptr& to); + + /// \brief View buffer + /// + /// Return a Buffer that reflects this buffer, seen potentially from another + /// device, without making an explicit copy of the contents. The underlying + /// mechanism is typically implemented by the kernel or device driver, and may + /// involve lazy caching of parts of the buffer contents on the destination + /// device's memory. + /// + /// If a non-copy view is unsupported for the buffer on the given device, + /// nullptr is returned. An error can be returned if some low-level + /// operation fails (such as an out-of-memory condition). + static Result> View(std::shared_ptr source, + const std::shared_ptr& to); + + /// \brief View or copy buffer + /// + /// Try to view buffer contents on the given MemoryManager's device, but + /// fall back to copying if a no-copy view isn't supported. + static Result> ViewOrCopy( + std::shared_ptr source, const std::shared_ptr& to); + + virtual std::shared_ptr device_sync_event() const { return NULLPTR; } + + protected: + bool is_mutable_; + bool is_cpu_; + const uint8_t* data_; + int64_t size_; + int64_t capacity_; + DeviceAllocationType device_type_; + + // null by default, but may be set + std::shared_ptr parent_; + + private: + // private so that subclasses are forced to call SetMemoryManager() + std::shared_ptr memory_manager_; + + protected: + Buffer(); + + void CheckMutable() const; + void CheckCPU() const; + + void SetMemoryManager(std::shared_ptr mm) { + memory_manager_ = std::move(mm); + is_cpu_ = memory_manager_->is_cpu(); + device_type_ = memory_manager_->device()->device_type(); + } +}; + +/// \defgroup buffer-slicing-functions Functions for slicing buffers +/// +/// @{ + +/// \brief Construct a view on a buffer at the given offset and length. +/// +/// This function cannot fail and does not check for errors (except in debug builds) +static inline std::shared_ptr SliceBuffer(std::shared_ptr buffer, + const int64_t offset, + const int64_t length) { + return std::make_shared(std::move(buffer), offset, length); +} + +/// \brief Construct a view on a buffer at the given offset, up to the buffer's end. +/// +/// This function cannot fail and does not check for errors (except in debug builds) +static inline std::shared_ptr SliceBuffer(std::shared_ptr buffer, + const int64_t offset) { + int64_t length = buffer->size() - offset; + return SliceBuffer(std::move(buffer), offset, length); +} + +/// \brief Input-checking version of SliceBuffer +/// +/// An Invalid Status is returned if the requested slice falls out of bounds. +ARROW_EXPORT +Result> SliceBufferSafe(std::shared_ptr buffer, + int64_t offset); +/// \brief Input-checking version of SliceBuffer +/// +/// An Invalid Status is returned if the requested slice falls out of bounds. +/// Note that unlike SliceBuffer, `length` isn't clamped to the available buffer size. +ARROW_EXPORT +Result> SliceBufferSafe(std::shared_ptr buffer, + int64_t offset, int64_t length); + +/// \brief Like SliceBuffer, but construct a mutable buffer slice. +/// +/// If the parent buffer is not mutable, behavior is undefined (it may abort +/// in debug builds). +ARROW_EXPORT +std::shared_ptr SliceMutableBuffer(std::shared_ptr buffer, + const int64_t offset, const int64_t length); + +/// \brief Like SliceBuffer, but construct a mutable buffer slice. +/// +/// If the parent buffer is not mutable, behavior is undefined (it may abort +/// in debug builds). +static inline std::shared_ptr SliceMutableBuffer(std::shared_ptr buffer, + const int64_t offset) { + int64_t length = buffer->size() - offset; + return SliceMutableBuffer(std::move(buffer), offset, length); +} + +/// \brief Input-checking version of SliceMutableBuffer +/// +/// An Invalid Status is returned if the requested slice falls out of bounds. +ARROW_EXPORT +Result> SliceMutableBufferSafe(std::shared_ptr buffer, + int64_t offset); +/// \brief Input-checking version of SliceMutableBuffer +/// +/// An Invalid Status is returned if the requested slice falls out of bounds. +/// Note that unlike SliceBuffer, `length` isn't clamped to the available buffer size. +ARROW_EXPORT +Result> SliceMutableBufferSafe(std::shared_ptr buffer, + int64_t offset, int64_t length); + +/// @} + +/// \class MutableBuffer +/// \brief A Buffer whose contents can be mutated. May or may not own its data. +class ARROW_EXPORT MutableBuffer : public Buffer { + public: + MutableBuffer(uint8_t* data, const int64_t size) : Buffer(data, size) { + is_mutable_ = true; + } + + MutableBuffer(uint8_t* data, const int64_t size, std::shared_ptr mm) + : Buffer(data, size, std::move(mm)) { + is_mutable_ = true; + } + + MutableBuffer(const std::shared_ptr& parent, const int64_t offset, + const int64_t size); + + /// \brief Create buffer referencing typed memory with some length + /// \param[in] data the typed memory as C array + /// \param[in] length the number of values in the array + /// \return a new shared_ptr + template + static std::shared_ptr Wrap(T* data, SizeType length) { + return std::make_shared(reinterpret_cast(data), + static_cast(sizeof(T) * length)); + } + + protected: + MutableBuffer() : Buffer(NULLPTR, 0) {} +}; + +/// \class ResizableBuffer +/// \brief A mutable buffer that can be resized +class ARROW_EXPORT ResizableBuffer : public MutableBuffer { + public: + /// Change buffer reported size to indicated size, allocating memory if + /// necessary. This will ensure that the capacity of the buffer is a multiple + /// of 64 bytes as defined in Layout.md. + /// Consider using ZeroPadding afterwards, to conform to the Arrow layout + /// specification. + /// + /// @param new_size The new size for the buffer. + /// @param shrink_to_fit Whether to shrink the capacity if new size < current size + virtual Status Resize(const int64_t new_size, bool shrink_to_fit) = 0; + Status Resize(const int64_t new_size) { + return Resize(new_size, /*shrink_to_fit=*/true); + } + + /// Ensure that buffer has enough memory allocated to fit the indicated + /// capacity (and meets the 64 byte padding requirement in Layout.md). + /// It does not change buffer's reported size and doesn't zero the padding. + virtual Status Reserve(const int64_t new_capacity) = 0; + + template + Status TypedResize(const int64_t new_nb_elements, bool shrink_to_fit = true) { + return Resize(sizeof(T) * new_nb_elements, shrink_to_fit); + } + + template + Status TypedReserve(const int64_t new_nb_elements) { + return Reserve(sizeof(T) * new_nb_elements); + } + + protected: + ResizableBuffer(uint8_t* data, int64_t size) : MutableBuffer(data, size) {} + ResizableBuffer(uint8_t* data, int64_t size, std::shared_ptr mm) + : MutableBuffer(data, size, std::move(mm)) {} +}; + +/// \defgroup buffer-allocation-functions Functions for allocating buffers +/// +/// @{ + +/// \brief Allocate a fixed size mutable buffer from a memory pool, zero its padding. +/// +/// \param[in] size size of buffer to allocate +/// \param[in] pool a memory pool +ARROW_EXPORT +Result> AllocateBuffer(const int64_t size, + MemoryPool* pool = NULLPTR); +ARROW_EXPORT +Result> AllocateBuffer(const int64_t size, int64_t alignment, + MemoryPool* pool = NULLPTR); + +/// \brief Allocate a resizeable buffer from a memory pool, zero its padding. +/// +/// \param[in] size size of buffer to allocate +/// \param[in] pool a memory pool +ARROW_EXPORT +Result> AllocateResizableBuffer( + const int64_t size, MemoryPool* pool = NULLPTR); +ARROW_EXPORT +Result> AllocateResizableBuffer( + const int64_t size, const int64_t alignment, MemoryPool* pool = NULLPTR); + +/// \brief Allocate a bitmap buffer from a memory pool +/// no guarantee on values is provided. +/// +/// \param[in] length size in bits of bitmap to allocate +/// \param[in] pool memory pool to allocate memory from +ARROW_EXPORT +Result> AllocateBitmap(int64_t length, + MemoryPool* pool = NULLPTR); + +/// \brief Allocate a zero-initialized bitmap buffer from a memory pool +/// +/// \param[in] length size in bits of bitmap to allocate +/// \param[in] pool memory pool to allocate memory from +ARROW_EXPORT +Result> AllocateEmptyBitmap(int64_t length, + MemoryPool* pool = NULLPTR); + +ARROW_EXPORT +Result> AllocateEmptyBitmap(int64_t length, int64_t alignment, + MemoryPool* pool = NULLPTR); + +/// \brief Concatenate multiple buffers into a single buffer +/// +/// \param[in] buffers to be concatenated +/// \param[in] pool memory pool to allocate the new buffer from +ARROW_EXPORT +Result> ConcatenateBuffers(const BufferVector& buffers, + MemoryPool* pool = NULLPTR); + +/// @} + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/buffer_builder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/buffer_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..e9177c656c021939405328fedd7a1e2704212650 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/buffer_builder.h @@ -0,0 +1,488 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/status.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/bitmap_generate.h" +#include "arrow/util/bitmap_ops.h" +#include "arrow/util/macros.h" +#include "arrow/util/ubsan.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +// ---------------------------------------------------------------------- +// Buffer builder classes + +/// \class BufferBuilder +/// \brief A class for incrementally building a contiguous chunk of in-memory +/// data +class ARROW_EXPORT BufferBuilder { + public: + explicit BufferBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : pool_(pool), + data_(/*ensure never null to make ubsan happy and avoid check penalties below*/ + util::MakeNonNull()), + capacity_(0), + size_(0), + alignment_(alignment) {} + + /// \brief Constructs new Builder that will start using + /// the provided buffer until Finish/Reset are called. + /// The buffer is not resized. + explicit BufferBuilder(std::shared_ptr buffer, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : buffer_(std::move(buffer)), + pool_(pool), + data_(buffer_->mutable_data()), + capacity_(buffer_->capacity()), + size_(buffer_->size()), + alignment_(alignment) {} + + /// \brief Resize the buffer to the nearest multiple of 64 bytes + /// + /// \param new_capacity the new capacity of the builder. Will be + /// rounded up to a multiple of 64 bytes for padding + /// \param shrink_to_fit if new capacity is smaller than the existing, + /// reallocate internal buffer. Set to false to avoid reallocations when + /// shrinking the builder. + /// \return Status + Status Resize(const int64_t new_capacity, bool shrink_to_fit = true) { + if (buffer_ == NULLPTR) { + ARROW_ASSIGN_OR_RAISE(buffer_, + AllocateResizableBuffer(new_capacity, alignment_, pool_)); + } else { + ARROW_RETURN_NOT_OK(buffer_->Resize(new_capacity, shrink_to_fit)); + } + capacity_ = buffer_->capacity(); + data_ = buffer_->mutable_data(); + return Status::OK(); + } + + /// \brief Ensure that builder can accommodate the additional number of bytes + /// without the need to perform allocations + /// + /// \param[in] additional_bytes number of additional bytes to make space for + /// \return Status + Status Reserve(const int64_t additional_bytes) { + auto min_capacity = size_ + additional_bytes; + if (min_capacity <= capacity_) { + return Status::OK(); + } + return Resize(GrowByFactor(capacity_, min_capacity), false); + } + + /// \brief Return a capacity expanded by the desired growth factor + static int64_t GrowByFactor(int64_t current_capacity, int64_t new_capacity) { + // Doubling capacity except for large Reserve requests. 2x growth strategy + // (versus 1.5x) seems to have slightly better performance when using + // jemalloc, but significantly better performance when using the system + // allocator. See ARROW-6450 for further discussion + return std::max(new_capacity, current_capacity * 2); + } + + /// \brief Append the given data to the buffer + /// + /// The buffer is automatically expanded if necessary. + Status Append(const void* data, const int64_t length) { + if (ARROW_PREDICT_FALSE(size_ + length > capacity_)) { + ARROW_RETURN_NOT_OK(Resize(GrowByFactor(capacity_, size_ + length), false)); + } + UnsafeAppend(data, length); + return Status::OK(); + } + + /// \brief Append the given data to the buffer + /// + /// The buffer is automatically expanded if necessary. + Status Append(std::string_view v) { return Append(v.data(), v.size()); } + + /// \brief Append copies of a value to the buffer + /// + /// The buffer is automatically expanded if necessary. + Status Append(const int64_t num_copies, uint8_t value) { + ARROW_RETURN_NOT_OK(Reserve(num_copies)); + UnsafeAppend(num_copies, value); + return Status::OK(); + } + + // Advance pointer and zero out memory + Status Advance(const int64_t length) { return Append(length, 0); } + + // Advance pointer, but don't allocate or zero memory + void UnsafeAdvance(const int64_t length) { size_ += length; } + + // Unsafe methods don't check existing size + void UnsafeAppend(const void* data, const int64_t length) { + memcpy(data_ + size_, data, static_cast(length)); + size_ += length; + } + + void UnsafeAppend(std::string_view v) { + UnsafeAppend(v.data(), static_cast(v.size())); + } + + void UnsafeAppend(const int64_t num_copies, uint8_t value) { + memset(data_ + size_, value, static_cast(num_copies)); + size_ += num_copies; + } + + /// \brief Return result of builder as a Buffer object. + /// + /// The builder is reset and can be reused afterwards. + /// + /// \param[out] out the finalized Buffer object + /// \param shrink_to_fit if the buffer size is smaller than its capacity, + /// reallocate to fit more tightly in memory. Set to false to avoid + /// a reallocation, at the expense of potentially more memory consumption. + /// \return Status + Status Finish(std::shared_ptr* out, bool shrink_to_fit = true) { + ARROW_RETURN_NOT_OK(Resize(size_, shrink_to_fit)); + if (size_ != 0) buffer_->ZeroPadding(); + *out = buffer_; + if (*out == NULLPTR) { + ARROW_ASSIGN_OR_RAISE(*out, AllocateBuffer(0, alignment_, pool_)); + } + Reset(); + return Status::OK(); + } + + Result> Finish(bool shrink_to_fit = true) { + std::shared_ptr out; + ARROW_RETURN_NOT_OK(Finish(&out, shrink_to_fit)); + return out; + } + + /// \brief Like Finish, but override the final buffer size + /// + /// This is useful after writing data directly into the builder memory + /// without calling the Append methods (basically, when using BufferBuilder + /// mostly for memory allocation). + Result> FinishWithLength(int64_t final_length, + bool shrink_to_fit = true) { + size_ = final_length; + return Finish(shrink_to_fit); + } + + void Reset() { + buffer_ = NULLPTR; + capacity_ = size_ = 0; + } + + /// \brief Set size to a smaller value without modifying builder + /// contents. For reusable BufferBuilder classes + /// \param[in] position must be non-negative and less than or equal + /// to the current length() + void Rewind(int64_t position) { size_ = position; } + + int64_t capacity() const { return capacity_; } + int64_t length() const { return size_; } + const uint8_t* data() const { return data_; } + uint8_t* mutable_data() { return data_; } + template + const T* data_as() const { + return reinterpret_cast(data_); + } + template + T* mutable_data_as() { + return reinterpret_cast(data_); + } + + private: + std::shared_ptr buffer_; + MemoryPool* pool_; + uint8_t* data_; + int64_t capacity_; + int64_t size_; + int64_t alignment_; +}; + +template +class TypedBufferBuilder; + +/// \brief A BufferBuilder for building a buffer of arithmetic elements +template +class TypedBufferBuilder< + T, typename std::enable_if::value || + std::is_standard_layout::value>::type> { + public: + explicit TypedBufferBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : bytes_builder_(pool, alignment) {} + + explicit TypedBufferBuilder(std::shared_ptr buffer, + MemoryPool* pool = default_memory_pool()) + : bytes_builder_(std::move(buffer), pool) {} + + explicit TypedBufferBuilder(BufferBuilder builder) + : bytes_builder_(std::move(builder)) {} + + BufferBuilder* bytes_builder() { return &bytes_builder_; } + + Status Append(T value) { + return bytes_builder_.Append(reinterpret_cast(&value), sizeof(T)); + } + + Status Append(const T* values, int64_t num_elements) { + return bytes_builder_.Append(reinterpret_cast(values), + num_elements * sizeof(T)); + } + + Status Append(const int64_t num_copies, T value) { + ARROW_RETURN_NOT_OK(Reserve(num_copies + length())); + UnsafeAppend(num_copies, value); + return Status::OK(); + } + + void UnsafeAppend(T value) { + bytes_builder_.UnsafeAppend(reinterpret_cast(&value), sizeof(T)); + } + + void UnsafeAppend(const T* values, int64_t num_elements) { + bytes_builder_.UnsafeAppend(reinterpret_cast(values), + num_elements * sizeof(T)); + } + + template + void UnsafeAppend(Iter values_begin, Iter values_end) { + auto num_elements = static_cast(std::distance(values_begin, values_end)); + auto data = mutable_data() + length(); + bytes_builder_.UnsafeAdvance(num_elements * sizeof(T)); + std::copy(values_begin, values_end, data); + } + + void UnsafeAppend(const int64_t num_copies, T value) { + auto data = mutable_data() + length(); + bytes_builder_.UnsafeAdvance(num_copies * sizeof(T)); + std::fill(data, data + num_copies, value); + } + + Status Resize(const int64_t new_capacity, bool shrink_to_fit = true) { + return bytes_builder_.Resize(new_capacity * sizeof(T), shrink_to_fit); + } + + Status Reserve(const int64_t additional_elements) { + return bytes_builder_.Reserve(additional_elements * sizeof(T)); + } + + Status Advance(const int64_t length) { + return bytes_builder_.Advance(length * sizeof(T)); + } + + void UnsafeAdvance(const int64_t length) { + bytes_builder_.UnsafeAdvance(length * sizeof(T)); + } + + Status Finish(std::shared_ptr* out, bool shrink_to_fit = true) { + return bytes_builder_.Finish(out, shrink_to_fit); + } + + Result> Finish(bool shrink_to_fit = true) { + std::shared_ptr out; + ARROW_RETURN_NOT_OK(Finish(&out, shrink_to_fit)); + return out; + } + + /// \brief Like Finish, but override the final buffer size + /// + /// This is useful after writing data directly into the builder memory + /// without calling the Append methods (basically, when using TypedBufferBuilder + /// only for memory allocation). + Result> FinishWithLength(int64_t final_length, + bool shrink_to_fit = true) { + return bytes_builder_.FinishWithLength(final_length * sizeof(T), shrink_to_fit); + } + + void Reset() { bytes_builder_.Reset(); } + + int64_t length() const { return bytes_builder_.length() / sizeof(T); } + int64_t capacity() const { return bytes_builder_.capacity() / sizeof(T); } + const T* data() const { return reinterpret_cast(bytes_builder_.data()); } + T* mutable_data() { return reinterpret_cast(bytes_builder_.mutable_data()); } + + private: + BufferBuilder bytes_builder_; +}; + +/// \brief A BufferBuilder for building a buffer containing a bitmap +template <> +class TypedBufferBuilder { + public: + explicit TypedBufferBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : bytes_builder_(pool, alignment) {} + + explicit TypedBufferBuilder(BufferBuilder builder) + : bytes_builder_(std::move(builder)) {} + + BufferBuilder* bytes_builder() { return &bytes_builder_; } + + Status Append(bool value) { + ARROW_RETURN_NOT_OK(Reserve(1)); + UnsafeAppend(value); + return Status::OK(); + } + + Status Append(const uint8_t* valid_bytes, int64_t num_elements) { + ARROW_RETURN_NOT_OK(Reserve(num_elements)); + UnsafeAppend(valid_bytes, num_elements); + return Status::OK(); + } + + Status Append(const int64_t num_copies, bool value) { + ARROW_RETURN_NOT_OK(Reserve(num_copies)); + UnsafeAppend(num_copies, value); + return Status::OK(); + } + + void UnsafeAppend(bool value) { + bit_util::SetBitTo(mutable_data(), bit_length_, value); + if (!value) { + ++false_count_; + } + ++bit_length_; + } + + /// \brief Append bits from an array of bytes (one value per byte) + void UnsafeAppend(const uint8_t* bytes, int64_t num_elements) { + if (num_elements == 0) return; + int64_t i = 0; + internal::GenerateBitsUnrolled(mutable_data(), bit_length_, num_elements, [&] { + bool value = bytes[i++]; + false_count_ += !value; + return value; + }); + bit_length_ += num_elements; + } + + /// \brief Append bits from a packed bitmap + void UnsafeAppend(const uint8_t* bitmap, int64_t offset, int64_t num_elements) { + if (num_elements == 0) return; + internal::CopyBitmap(bitmap, offset, num_elements, mutable_data(), bit_length_); + false_count_ += num_elements - internal::CountSetBits(bitmap, offset, num_elements); + bit_length_ += num_elements; + } + + void UnsafeAppend(const int64_t num_copies, bool value) { + bit_util::SetBitsTo(mutable_data(), bit_length_, num_copies, value); + false_count_ += num_copies * !value; + bit_length_ += num_copies; + } + + template + void UnsafeAppend(const int64_t num_elements, Generator&& gen) { + if (num_elements == 0) return; + + if (count_falses) { + internal::GenerateBitsUnrolled(mutable_data(), bit_length_, num_elements, [&] { + bool value = gen(); + false_count_ += !value; + return value; + }); + } else { + internal::GenerateBitsUnrolled(mutable_data(), bit_length_, num_elements, + std::forward(gen)); + } + bit_length_ += num_elements; + } + + Status Resize(const int64_t new_capacity, bool shrink_to_fit = true) { + const int64_t old_byte_capacity = bytes_builder_.capacity(); + ARROW_RETURN_NOT_OK( + bytes_builder_.Resize(bit_util::BytesForBits(new_capacity), shrink_to_fit)); + // Resize() may have chosen a larger capacity (e.g. for padding), + // so ask it again before calling memset(). + const int64_t new_byte_capacity = bytes_builder_.capacity(); + if (new_byte_capacity > old_byte_capacity) { + // The additional buffer space is 0-initialized for convenience, + // so that other methods can simply bump the length. + memset(mutable_data() + old_byte_capacity, 0, + static_cast(new_byte_capacity - old_byte_capacity)); + } + return Status::OK(); + } + + Status Reserve(const int64_t additional_elements) { + return Resize( + BufferBuilder::GrowByFactor(bit_length_, bit_length_ + additional_elements), + false); + } + + Status Advance(const int64_t length) { + ARROW_RETURN_NOT_OK(Reserve(length)); + bit_length_ += length; + false_count_ += length; + return Status::OK(); + } + + Status Finish(std::shared_ptr* out, bool shrink_to_fit = true) { + // set bytes_builder_.size_ == byte size of data + bytes_builder_.UnsafeAdvance(bit_util::BytesForBits(bit_length_) - + bytes_builder_.length()); + bit_length_ = false_count_ = 0; + return bytes_builder_.Finish(out, shrink_to_fit); + } + + Result> Finish(bool shrink_to_fit = true) { + std::shared_ptr out; + ARROW_RETURN_NOT_OK(Finish(&out, shrink_to_fit)); + return out; + } + + /// \brief Like Finish, but override the final buffer size + /// + /// This is useful after writing data directly into the builder memory + /// without calling the Append methods (basically, when using TypedBufferBuilder + /// only for memory allocation). + Result> FinishWithLength(int64_t final_length, + bool shrink_to_fit = true) { + const auto final_byte_length = bit_util::BytesForBits(final_length); + bytes_builder_.UnsafeAdvance(final_byte_length - bytes_builder_.length()); + bit_length_ = false_count_ = 0; + return bytes_builder_.FinishWithLength(final_byte_length, shrink_to_fit); + } + + void Reset() { + bytes_builder_.Reset(); + bit_length_ = false_count_ = 0; + } + + int64_t length() const { return bit_length_; } + int64_t capacity() const { return bytes_builder_.capacity() * 8; } + const uint8_t* data() const { return bytes_builder_.data(); } + uint8_t* mutable_data() { return bytes_builder_.mutable_data(); } + int64_t false_count() const { return false_count_; } + + private: + BufferBuilder bytes_builder_; + int64_t bit_length_ = 0; + int64_t false_count_ = 0; +}; + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/builder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/builder.h new file mode 100644 index 0000000000000000000000000000000000000000..f0aa14c1e0612d1872a5959998651a12668f449f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/builder.h @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/array/builder_adaptive.h" // IWYU pragma: keep +#include "arrow/array/builder_base.h" // IWYU pragma: keep +#include "arrow/array/builder_binary.h" // IWYU pragma: keep +#include "arrow/array/builder_decimal.h" // IWYU pragma: keep +#include "arrow/array/builder_dict.h" // IWYU pragma: keep +#include "arrow/array/builder_nested.h" // IWYU pragma: keep +#include "arrow/array/builder_primitive.h" // IWYU pragma: keep +#include "arrow/array/builder_run_end.h" // IWYU pragma: keep +#include "arrow/array/builder_time.h" // IWYU pragma: keep +#include "arrow/array/builder_union.h" // IWYU pragma: keep +#include "arrow/status.h" +#include "arrow/util/visibility.h" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/chunk_resolver.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/chunk_resolver.h new file mode 100644 index 0000000000000000000000000000000000000000..3d6458167fac979c2d6c6c112fa00194b9818092 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/chunk_resolver.h @@ -0,0 +1,294 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/span.h" + +namespace arrow { + +class ChunkResolver; + +template +struct ARROW_EXPORT TypedChunkLocation { + /// \brief Index of the chunk in the array of chunks + /// + /// The value is always in the range `[0, chunks.size()]`. `chunks.size()` is used + /// to represent out-of-bounds locations. + IndexType chunk_index = 0; + + /// \brief Index of the value in the chunk + /// + /// The value is UNDEFINED if `chunk_index >= chunks.size()` + IndexType index_in_chunk = 0; + + TypedChunkLocation() = default; + + TypedChunkLocation(IndexType chunk_index, IndexType index_in_chunk) + : chunk_index(chunk_index), index_in_chunk(index_in_chunk) { + static_assert(sizeof(TypedChunkLocation) == 2 * sizeof(IndexType)); + static_assert(alignof(TypedChunkLocation) == alignof(IndexType)); + } + + bool operator==(TypedChunkLocation other) const { + return chunk_index == other.chunk_index && index_in_chunk == other.index_in_chunk; + } +}; + +using ChunkLocation = TypedChunkLocation; + +/// \brief An utility that incrementally resolves logical indices into +/// physical indices in a chunked array. +class ARROW_EXPORT ChunkResolver { + private: + /// \brief Array containing `chunks.size() + 1` offsets. + /// + /// `offsets_[i]` is the starting logical index of chunk `i`. `offsets_[0]` is always 0 + /// and `offsets_[chunks.size()]` is the logical length of the chunked array. + std::vector offsets_; + + /// \brief Cache of the index of the last resolved chunk. + /// + /// \invariant `cached_chunk_ in [0, chunks.size()]` + mutable std::atomic cached_chunk_; + + public: + explicit ChunkResolver(const ArrayVector& chunks) noexcept; + explicit ChunkResolver(util::span chunks) noexcept; + explicit ChunkResolver(const RecordBatchVector& batches) noexcept; + + /// \brief Construct a ChunkResolver from a vector of chunks.size() + 1 offsets. + /// + /// The first offset must be 0 and the last offset must be the logical length of the + /// chunked array. Each offset before the last represents the starting logical index of + /// the corresponding chunk. + explicit ChunkResolver(std::vector offsets) noexcept + : offsets_(std::move(offsets)), cached_chunk_(0) { +#ifndef NDEBUG + assert(offsets_.size() >= 1); + assert(offsets_[0] == 0); + for (size_t i = 1; i < offsets_.size(); i++) { + assert(offsets_[i] >= offsets_[i - 1]); + } + assert(offsets_.size() - 1 <= + static_cast(std::numeric_limits::max())); +#endif + } + + ChunkResolver(ChunkResolver&& other) noexcept; + ChunkResolver& operator=(ChunkResolver&& other) noexcept; + + ChunkResolver(const ChunkResolver& other) noexcept; + ChunkResolver& operator=(const ChunkResolver& other) noexcept; + + int64_t logical_array_length() const { return offsets_.back(); } + int32_t num_chunks() const { return static_cast(offsets_.size() - 1); } + + int64_t chunk_length(int64_t chunk_index) const { + return offsets_[chunk_index + 1] - offsets_[chunk_index]; + } + + /// \brief Resolve a logical index to a ChunkLocation. + /// + /// The returned ChunkLocation contains the chunk index and the within-chunk index + /// equivalent to the logical index. + /// + /// \pre `index >= 0` + /// \post `location.chunk_index` in `[0, chunks.size()]` + /// \param index The logical index to resolve + /// \return ChunkLocation with a valid chunk_index if index is within + /// bounds, or with `chunk_index == chunks.size()` if logical index is + /// `>= chunked_array.length()`. + inline ChunkLocation Resolve(int64_t index) const { + const auto cached_chunk = cached_chunk_.load(std::memory_order_relaxed); + const auto chunk_index = + ResolveChunkIndex(index, cached_chunk); + return ChunkLocation{chunk_index, index - offsets_[chunk_index]}; + } + + /// \brief Resolve a logical index to a ChunkLocation. + /// + /// The returned ChunkLocation contains the chunk index and the within-chunk index + /// equivalent to the logical index. + /// + /// \pre `index >= 0` + /// \post `location.chunk_index` in `[0, chunks.size()]` + /// \param index The logical index to resolve + /// \param hint ChunkLocation{} or the last ChunkLocation returned by + /// this ChunkResolver. + /// \return ChunkLocation with a valid chunk_index if index is within + /// bounds, or with `chunk_index == chunks.size()` if logical index is + /// `>= chunked_array.length()`. + inline ChunkLocation ResolveWithHint(int64_t index, ChunkLocation hint) const { + assert(hint.chunk_index < static_cast(offsets_.size())); + const auto chunk_index = ResolveChunkIndex( + index, static_cast(hint.chunk_index)); + return ChunkLocation{chunk_index, index - offsets_[chunk_index]}; + } + + /// \brief Resolve `n_indices` logical indices to chunk indices. + /// + /// \pre 0 <= logical_index_vec[i] < logical_array_length() + /// (for well-defined and valid chunk index results) + /// \pre out_chunk_location_vec has space for `n_indices` locations + /// \pre chunk_hint in [0, chunks.size()] + /// \post out_chunk_location_vec[i].chunk_index in [0, chunks.size()] for i in [0, n) + /// \post if logical_index_vec[i] >= chunked_array.length(), then + /// out_chunk_location_vec[i].chunk_index == chunks.size() + /// and out_chunk_location_vec[i].index_in_chunk is UNDEFINED (can be + /// out-of-bounds) + /// \post if logical_index_vec[i] < 0, then both values in out_chunk_index_vec[i] + /// are UNDEFINED + /// + /// \param n_indices The number of logical indices to resolve + /// \param logical_index_vec The logical indices to resolve + /// \param out_chunk_location_vec The output array where the locations will be written + /// \param chunk_hint 0 or the last chunk_index produced by ResolveMany + /// \return false iff chunks.size() > std::numeric_limits::max() + template + [[nodiscard]] bool ResolveMany(int64_t n_indices, const IndexType* logical_index_vec, + TypedChunkLocation* out_chunk_location_vec, + IndexType chunk_hint = 0) const { + if constexpr (sizeof(IndexType) < sizeof(uint32_t)) { + // The max value returned by Bisect is `offsets.size() - 1` (= chunks.size()). + constexpr int64_t kMaxIndexTypeValue = std::numeric_limits::max(); + // A ChunkedArray with enough empty chunks can make the index of a chunk + // exceed the logical index and thus the maximum value of IndexType. + const bool chunk_index_fits_on_type = num_chunks() <= kMaxIndexTypeValue; + if (ARROW_PREDICT_FALSE(!chunk_index_fits_on_type)) { + return false; + } + // Since an index-in-chunk cannot possibly exceed the logical index being + // queried, we don't have to worry about these values not fitting on IndexType. + } + if constexpr (std::is_signed_v) { + // We interpret signed integers as unsigned and avoid having to generate double + // the amount of binary code to handle each integer width. + // + // Negative logical indices can become large values when cast to unsigned, and + // they are gracefully handled by ResolveManyImpl, but both the chunk index + // and the index in chunk values will be undefined in these cases. This + // happend because int8_t(-1) == uint8_t(255) and 255 could be a valid + // logical index in the chunked array. + using U = std::make_unsigned_t; + ResolveManyImpl(n_indices, reinterpret_cast(logical_index_vec), + reinterpret_cast*>(out_chunk_location_vec), + static_cast(chunk_hint)); + } else { + static_assert(std::is_unsigned_v); + ResolveManyImpl(n_indices, logical_index_vec, out_chunk_location_vec, + static_cast(chunk_hint)); + } + return true; + } + + private: + template + inline int64_t ResolveChunkIndex(int64_t index, int32_t cached_chunk) const { + // It is common for algorithms sequentially processing arrays to make consecutive + // accesses at a relatively small distance from each other, hence often falling in the + // same chunk. + // + // This is guaranteed when merging (assuming each side of the merge uses its + // own resolver), and is the most common case in recursive invocations of + // partitioning. + const auto num_offsets = static_cast(offsets_.size()); + const int64_t* offsets = offsets_.data(); + if (ARROW_PREDICT_TRUE(index >= offsets[cached_chunk]) && + (static_cast(cached_chunk + 1) == num_offsets || + index < offsets[cached_chunk + 1])) { + return cached_chunk; + } + // lo < hi is guaranteed by `num_offsets = chunks.size() + 1` + const auto chunk_index = Bisect(index, offsets, /*lo=*/0, /*hi=*/num_offsets); + if constexpr (StoreCachedChunk) { + assert(static_cast(chunk_index) < static_cast(offsets_.size())); + cached_chunk_.store(chunk_index, std::memory_order_relaxed); + } + return chunk_index; + } + + /// \pre all the pre-conditions of ChunkResolver::ResolveMany() + /// \pre num_offsets - 1 <= std::numeric_limits::max() + void ResolveManyImpl(int64_t, const uint8_t*, TypedChunkLocation*, + int32_t) const; + void ResolveManyImpl(int64_t, const uint16_t*, TypedChunkLocation*, + int32_t) const; + void ResolveManyImpl(int64_t, const uint32_t*, TypedChunkLocation*, + int32_t) const; + void ResolveManyImpl(int64_t, const uint64_t*, TypedChunkLocation*, + int32_t) const; + + public: + /// \brief Find the index of the chunk that contains the logical index. + /// + /// Any non-negative index is accepted. When `hi=num_offsets`, the largest + /// possible return value is `num_offsets-1` which is equal to + /// `chunks.size()`. Which is returned when the logical index is greater or + /// equal the logical length of the chunked array. + /// + /// \pre index >= 0 (otherwise, when index is negative, hi-1 is returned) + /// \pre lo < hi + /// \pre lo >= 0 && hi <= offsets_.size() + static inline int32_t Bisect(int64_t index, const int64_t* offsets, int32_t lo, + int32_t hi) { + return Bisect(static_cast(index), + reinterpret_cast(offsets), static_cast(lo), + static_cast(hi)); + } + + static inline int32_t Bisect(uint64_t index, const uint64_t* offsets, uint32_t lo, + uint32_t hi) { + // Similar to std::upper_bound(), but slightly different as our offsets + // array always starts with 0. + auto n = hi - lo; + // First iteration does not need to check for n > 1 + // (lo < hi is guaranteed by the precondition). + assert(n > 1 && "lo < hi is a precondition of Bisect"); + do { + const uint32_t m = n >> 1; + const uint32_t mid = lo + m; + if (index >= offsets[mid]) { + lo = mid; + n -= m; + } else { + n = m; + } + } while (n > 1); + return lo; + } +}; + +// Explicitly instantiate template base struct, for DLL linking on Windows +template struct TypedChunkLocation; +template struct TypedChunkLocation; +template struct TypedChunkLocation; +template struct TypedChunkLocation; +template struct TypedChunkLocation; +template struct TypedChunkLocation; +template struct TypedChunkLocation; +template struct TypedChunkLocation; +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/chunked_array.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/chunked_array.h new file mode 100644 index 0000000000000000000000000000000000000000..02bcd0f9026bc7ba8ac9ef2daf2a3bd7ab31d56f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/chunked_array.h @@ -0,0 +1,283 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/chunk_resolver.h" +#include "arrow/compare.h" +#include "arrow/device_allocation_type_set.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class Array; +class DataType; +class MemoryPool; +namespace stl { +template +class ChunkedArrayIterator; +} // namespace stl + +/// \class ChunkedArray +/// \brief A data structure managing a list of primitive Arrow arrays logically +/// as one large array +/// +/// Data chunking is treated throughout this project largely as an +/// implementation detail for performance and memory use optimization. +/// ChunkedArray allows Array objects to be collected and interpreted +/// as a single logical array without requiring an expensive concatenation +/// step. +/// +/// In some cases, data produced by a function may exceed the capacity of an +/// Array (like BinaryArray or StringArray) and so returning multiple Arrays is +/// the only possibility. In these cases, we recommend returning a ChunkedArray +/// instead of vector of Arrays or some alternative. +/// +/// When data is processed in parallel, it may not be practical or possible to +/// create large contiguous memory allocations and write output into them. With +/// some data types, like binary and string types, it is not possible at all to +/// produce non-chunked array outputs without requiring a concatenation step at +/// the end of processing. +/// +/// Application developers may tune chunk sizes based on analysis of +/// performance profiles but many developer-users will not need to be +/// especially concerned with the chunking details. +/// +/// Preserving the chunk layout/sizes in processing steps is generally not +/// considered to be a contract in APIs. A function may decide to alter the +/// chunking of its result. Similarly, APIs accepting multiple ChunkedArray +/// inputs should not expect the chunk layout to be the same in each input. +class ARROW_EXPORT ChunkedArray { + public: + ChunkedArray(ChunkedArray&&) = default; + ChunkedArray& operator=(ChunkedArray&&) = default; + + /// \brief Construct a chunked array from a single Array + explicit ChunkedArray(std::shared_ptr chunk) + : ChunkedArray(ArrayVector{std::move(chunk)}) {} + + /// \brief Construct a chunked array from a vector of arrays and an optional data type + /// + /// The vector elements must have the same data type. + /// If the data type is passed explicitly, the vector may be empty. + /// If the data type is omitted, the vector must be non-empty. + explicit ChunkedArray(ArrayVector chunks, std::shared_ptr type = NULLPTR); + + // \brief Constructor with basic input validation. + static Result> Make( + ArrayVector chunks, std::shared_ptr type = NULLPTR); + + /// \brief Create an empty ChunkedArray of a given type + /// + /// The output ChunkedArray will have one chunk with an empty + /// array of the given type. + /// + /// \param[in] type the data type of the empty ChunkedArray + /// \param[in] pool the memory pool to allocate memory from + /// \return the resulting ChunkedArray + static Result> MakeEmpty( + std::shared_ptr type, MemoryPool* pool = default_memory_pool()); + + /// \return the total length of the chunked array; computed on construction + int64_t length() const { return length_; } + + /// \return the total number of nulls among all chunks + int64_t null_count() const { return null_count_; } + + /// \return the total number of chunks in the chunked array + int num_chunks() const { return static_cast(chunks_.size()); } + + /// \return chunk a particular chunk from the chunked array + const std::shared_ptr& chunk(int i) const { return chunks_[i]; } + + /// \return an ArrayVector of chunks + const ArrayVector& chunks() const { return chunks_; } + + /// \return The set of device allocation types used by the chunks in this + /// chunked array. + DeviceAllocationTypeSet device_types() const; + + /// \return true if all chunks are allocated on CPU-accessible memory. + bool is_cpu() const { return device_types().is_cpu_only(); } + + /// \brief Construct a zero-copy slice of the chunked array with the + /// indicated offset and length + /// + /// \param[in] offset the position of the first element in the constructed + /// slice + /// \param[in] length the length of the slice. If there are not enough + /// elements in the chunked array, the length will be adjusted accordingly + /// + /// \return a new object wrapped in std::shared_ptr + std::shared_ptr Slice(int64_t offset, int64_t length) const; + + /// \brief Slice from offset until end of the chunked array + std::shared_ptr Slice(int64_t offset) const; + + /// \brief Flatten this chunked array as a vector of chunked arrays, one + /// for each struct field + /// + /// \param[in] pool The pool for buffer allocations, if any + Result>> Flatten( + MemoryPool* pool = default_memory_pool()) const; + + /// Construct a zero-copy view of this chunked array with the given + /// type. Calls Array::View on each constituent chunk. Always succeeds if + /// there are zero chunks + Result> View(const std::shared_ptr& type) const; + + /// \brief Return the type of the chunked array + const std::shared_ptr& type() const { return type_; } + + /// \brief Return a Scalar containing the value of this array at index + Result> GetScalar(int64_t index) const; + + /// \brief Determine if two chunked arrays are equal. + /// + /// Two chunked arrays can be equal only if they have equal datatypes. + /// However, they may be equal even if they have different chunkings. + bool Equals(const ChunkedArray& other, + const EqualOptions& opts = EqualOptions::Defaults()) const; + /// \brief Determine if two chunked arrays are equal. + bool Equals(const std::shared_ptr& other, + const EqualOptions& opts = EqualOptions::Defaults()) const; + /// \brief Determine if two chunked arrays approximately equal + bool ApproxEquals(const ChunkedArray& other, + const EqualOptions& = EqualOptions::Defaults()) const; + + /// \return PrettyPrint representation suitable for debugging + std::string ToString() const; + + /// \brief Perform cheap validation checks to determine obvious inconsistencies + /// within the chunk array's internal data. + /// + /// This is O(k*m) where k is the number of array descendents, + /// and m is the number of chunks. + /// + /// \return Status + Status Validate() const; + + /// \brief Perform extensive validation checks to determine inconsistencies + /// within the chunk array's internal data. + /// + /// This is O(k*n) where k is the number of array descendents, + /// and n is the length in elements. + /// + /// \return Status + Status ValidateFull() const; + + protected: + ArrayVector chunks_; + std::shared_ptr type_; + int64_t length_; + int64_t null_count_; + + private: + template + friend class ::arrow::stl::ChunkedArrayIterator; + ChunkResolver chunk_resolver_; + ARROW_DISALLOW_COPY_AND_ASSIGN(ChunkedArray); +}; + +namespace internal { + +/// \brief EXPERIMENTAL: Utility for incremental iteration over contiguous +/// pieces of potentially differently-chunked ChunkedArray objects +class ARROW_EXPORT MultipleChunkIterator { + public: + MultipleChunkIterator(const ChunkedArray& left, const ChunkedArray& right) + : left_(left), + right_(right), + pos_(0), + length_(left.length()), + chunk_idx_left_(0), + chunk_idx_right_(0), + chunk_pos_left_(0), + chunk_pos_right_(0) {} + + bool Next(std::shared_ptr* next_left, std::shared_ptr* next_right); + + int64_t position() const { return pos_; } + + private: + const ChunkedArray& left_; + const ChunkedArray& right_; + + // The amount of the entire ChunkedArray consumed + int64_t pos_; + + // Length of the chunked array(s) + int64_t length_; + + // Current left chunk + int chunk_idx_left_; + + // Current right chunk + int chunk_idx_right_; + + // Offset into the current left chunk + int64_t chunk_pos_left_; + + // Offset into the current right chunk + int64_t chunk_pos_right_; +}; + +/// \brief Evaluate binary function on two ChunkedArray objects having possibly +/// different chunk layouts. The passed binary function / functor should have +/// the following signature. +/// +/// Status(const Array&, const Array&, int64_t) +/// +/// The third argument is the absolute position relative to the start of each +/// ChunkedArray. The function is executed against each contiguous pair of +/// array segments, slicing if necessary. +/// +/// For example, if two arrays have chunk sizes +/// +/// left: [10, 10, 20] +/// right: [15, 10, 15] +/// +/// Then the following invocations take place (pseudocode) +/// +/// func(left.chunk[0][0:10], right.chunk[0][0:10], 0) +/// func(left.chunk[1][0:5], right.chunk[0][10:15], 10) +/// func(left.chunk[1][5:10], right.chunk[1][0:5], 15) +/// func(left.chunk[2][0:5], right.chunk[1][5:10], 20) +/// func(left.chunk[2][5:20], right.chunk[2][:], 25) +template +Status ApplyBinaryChunked(const ChunkedArray& left, const ChunkedArray& right, + Action&& action) { + MultipleChunkIterator iterator(left, right); + std::shared_ptr left_piece, right_piece; + while (iterator.Next(&left_piece, &right_piece)) { + ARROW_RETURN_NOT_OK(action(*left_piece, *right_piece, iterator.position())); + } + return Status::OK(); +} + +} // namespace internal +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compare.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compare.h new file mode 100644 index 0000000000000000000000000000000000000000..2198495d7d20371d86aef50b8beb00541d323e74 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compare.h @@ -0,0 +1,213 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Functions for comparing Arrow data structures + +#pragma once + +#include +#include + +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +struct ArrayStatistics; +class Array; +class DataType; +class Tensor; +class SparseTensor; +struct Scalar; + +static constexpr double kDefaultAbsoluteTolerance = 1E-5; + +/// A container of options for equality comparisons +class EqualOptions { + public: + /// Whether or not NaNs are considered equal. + bool nans_equal() const { return nans_equal_; } + + /// Return a new EqualOptions object with the "nans_equal" property changed. + EqualOptions nans_equal(bool v) const { + auto res = EqualOptions(*this); + res.nans_equal_ = v; + return res; + } + + /// Whether or not zeros with differing signs are considered equal. + bool signed_zeros_equal() const { return signed_zeros_equal_; } + + /// Return a new EqualOptions object with the "signed_zeros_equal" property changed. + EqualOptions signed_zeros_equal(bool v) const { + auto res = EqualOptions(*this); + res.signed_zeros_equal_ = v; + return res; + } + + /// Whether the "atol" property is used in the comparison. + /// + /// This option only affects the Equals methods + /// and has no effect on ApproxEquals methods. + bool use_atol() const { return use_atol_; } + + /// Return a new EqualOptions object with the "use_atol" property changed. + EqualOptions use_atol(bool v) const { + auto res = EqualOptions(*this); + res.use_atol_ = v; + return res; + } + + /// The absolute tolerance for approximate comparisons of floating-point values. + /// Note that this option is ignored if "use_atol" is set to false. + double atol() const { return atol_; } + + /// Return a new EqualOptions object with the "atol" property changed. + EqualOptions atol(double v) const { + auto res = EqualOptions(*this); + res.atol_ = v; + return res; + } + + /// Whether the \ref arrow::Schema property is used in the comparison. + /// + /// This option only affects the Equals methods + /// and has no effect on ApproxEquals methods. + bool use_schema() const { return use_schema_; } + + /// Return a new EqualOptions object with the "use_schema_" property changed. + /// + /// Setting this option is false making the value of \ref EqualOptions::use_metadata + /// is ignored. + EqualOptions use_schema(bool v) const { + auto res = EqualOptions(*this); + res.use_schema_ = v; + return res; + } + + /// Whether the "metadata" in \ref arrow::Schema is used in the comparison. + /// + /// This option only affects the Equals methods + /// and has no effect on the ApproxEquals methods. + /// + /// Note: This option is only considered when \ref arrow::EqualOptions::use_schema is + /// set to true. + bool use_metadata() const { return use_metadata_; } + + /// Return a new EqualOptions object with the "use_metadata" property changed. + EqualOptions use_metadata(bool v) const { + auto res = EqualOptions(*this); + res.use_metadata_ = v; + return res; + } + + /// The ostream to which a diff will be formatted if arrays disagree. + /// If this is null (the default) no diff will be formatted. + std::ostream* diff_sink() const { return diff_sink_; } + + /// Return a new EqualOptions object with the "diff_sink" property changed. + /// This option will be ignored if diff formatting of the types of compared arrays is + /// not supported. + EqualOptions diff_sink(std::ostream* diff_sink) const { + auto res = EqualOptions(*this); + res.diff_sink_ = diff_sink; + return res; + } + + static EqualOptions Defaults() { return {}; } + + protected: + double atol_ = kDefaultAbsoluteTolerance; + bool nans_equal_ = false; + bool signed_zeros_equal_ = true; + bool use_atol_ = false; + bool use_schema_ = true; + bool use_metadata_ = false; + + std::ostream* diff_sink_ = NULLPTR; +}; + +/// Returns true if the arrays are exactly equal +/// +/// Note that arrow::ArrayStatistics is not included in the comparison. +ARROW_EXPORT bool ArrayEquals(const Array& left, const Array& right, + const EqualOptions& = EqualOptions::Defaults()); + +/// Returns true if the arrays are approximately equal. For non-floating point +/// types, this is equivalent to ArrayEquals(left, right) +/// +/// Note that arrow::ArrayStatistics is not included in the comparison. +ARROW_EXPORT bool ArrayApproxEquals(const Array& left, const Array& right, + const EqualOptions& = EqualOptions::Defaults()); + +/// Returns true if indicated equal-length segment of arrays are exactly equal +/// +/// Note that arrow::ArrayStatistics is not included in the comparison. +ARROW_EXPORT bool ArrayRangeEquals(const Array& left, const Array& right, + int64_t start_idx, int64_t end_idx, + int64_t other_start_idx, + const EqualOptions& = EqualOptions::Defaults()); + +/// Returns true if indicated equal-length segment of arrays are approximately equal +/// +/// Note that arrow::ArrayStatistics is not included in the comparison. +ARROW_EXPORT bool ArrayRangeApproxEquals(const Array& left, const Array& right, + int64_t start_idx, int64_t end_idx, + int64_t other_start_idx, + const EqualOptions& = EqualOptions::Defaults()); + +ARROW_EXPORT bool TensorEquals(const Tensor& left, const Tensor& right, + const EqualOptions& = EqualOptions::Defaults()); + +/// EXPERIMENTAL: Returns true if the given sparse tensors are exactly equal +ARROW_EXPORT bool SparseTensorEquals(const SparseTensor& left, const SparseTensor& right, + const EqualOptions& = EqualOptions::Defaults()); + +/// Returns true if the type metadata are exactly equal +/// \param[in] left a DataType +/// \param[in] right a DataType +/// \param[in] check_metadata whether to compare KeyValueMetadata for child +/// fields +ARROW_EXPORT bool TypeEquals(const DataType& left, const DataType& right, + bool check_metadata = true); + +/// \brief Check two \ref arrow::ArrayStatistics for equality +/// \param[in] left an \ref arrow::ArrayStatistics +/// \param[in] right an \ref arrow::ArrayStatistics +/// \param[in] options Options used to compare double values for equality. +/// \return True if the two \ref arrow::ArrayStatistics instances are equal; otherwise, +/// false. +ARROW_EXPORT bool ArrayStatisticsEquals( + const ArrayStatistics& left, const ArrayStatistics& right, + const EqualOptions& options = EqualOptions::Defaults()); + +/// Returns true if scalars are equal +/// \param[in] left a Scalar +/// \param[in] right a Scalar +/// \param[in] options comparison options +ARROW_EXPORT bool ScalarEquals(const Scalar& left, const Scalar& right, + const EqualOptions& options = EqualOptions::Defaults()); + +/// Returns true if scalars are approximately equal +/// \param[in] left a Scalar +/// \param[in] right a Scalar +/// \param[in] options comparison options +ARROW_EXPORT bool ScalarApproxEquals( + const Scalar& left, const Scalar& right, + const EqualOptions& options = EqualOptions::Defaults()); + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api.h new file mode 100644 index 0000000000000000000000000000000000000000..343e30643cfd31916caafc4a84a3fd393c9a84ef --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api.h @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle + +#pragma once + +/// \defgroup compute-functions Abstract compute function API +/// @{ +/// @} + +/// \defgroup compute-concrete-options Concrete option classes for compute functions +/// @{ +/// @} + +#include "arrow/compute/api_aggregate.h" // IWYU pragma: export +#include "arrow/compute/api_scalar.h" // IWYU pragma: export +#include "arrow/compute/api_vector.h" // IWYU pragma: export +#include "arrow/compute/cast.h" // IWYU pragma: export +#include "arrow/compute/function.h" // IWYU pragma: export +#include "arrow/compute/function_options.h" // IWYU pragma: export +#include "arrow/compute/initialize.h" // IWYU pragma: export +#include "arrow/compute/kernel.h" // IWYU pragma: export +#include "arrow/compute/registry.h" // IWYU pragma: export +#include "arrow/datum.h" // IWYU pragma: export + +#include "arrow/compute/expression.h" // IWYU pragma: export + +/// \defgroup execnode-row Utilities for working with data in a row-major format +/// @{ +/// @} + +#include "arrow/compute/row/grouper.h" // IWYU pragma: export + +/// \defgroup acero-internals Acero internals, useful for those extending Acero +/// @{ +/// @} + +#include "arrow/compute/exec.h" // IWYU pragma: export diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_aggregate.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_aggregate.h new file mode 100644 index 0000000000000000000000000000000000000000..d31e0a73156dc8007e0fefaeabc5e9b3e60618fa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_aggregate.h @@ -0,0 +1,596 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Eager evaluation convenience APIs for invoking common functions, including +// necessary memory allocations + +#pragma once + +#include + +#include "arrow/compute/function_options.h" +#include "arrow/datum.h" +#include "arrow/result.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class Array; + +namespace compute { + +class ExecContext; + +// ---------------------------------------------------------------------- +// Aggregate functions + +/// \addtogroup compute-concrete-options +/// @{ + +/// \brief Control general scalar aggregate kernel behavior +/// +/// By default, null values are ignored (skip_nulls = true). +class ARROW_EXPORT ScalarAggregateOptions : public FunctionOptions { + public: + explicit ScalarAggregateOptions(bool skip_nulls = true, uint32_t min_count = 1); + static constexpr const char kTypeName[] = "ScalarAggregateOptions"; + static ScalarAggregateOptions Defaults() { return ScalarAggregateOptions{}; } + + /// If true (the default), null values are ignored. Otherwise, if any value is null, + /// emit null. + bool skip_nulls; + /// If less than this many non-null values are observed, emit null. + uint32_t min_count; +}; + +/// \brief Control count aggregate kernel behavior. +/// +/// By default, only non-null values are counted. +class ARROW_EXPORT CountOptions : public FunctionOptions { + public: + enum CountMode { + /// Count only non-null values. + ONLY_VALID = 0, + /// Count only null values. + ONLY_NULL, + /// Count both non-null and null values. + ALL, + }; + explicit CountOptions(CountMode mode = CountMode::ONLY_VALID); + static constexpr const char kTypeName[] = "CountOptions"; + static CountOptions Defaults() { return CountOptions{}; } + + CountMode mode; +}; + +/// \brief Control Mode kernel behavior +/// +/// Returns top-n common values and counts. +/// By default, returns the most common value and count. +class ARROW_EXPORT ModeOptions : public FunctionOptions { + public: + explicit ModeOptions(int64_t n = 1, bool skip_nulls = true, uint32_t min_count = 0); + static constexpr const char kTypeName[] = "ModeOptions"; + static ModeOptions Defaults() { return ModeOptions{}; } + + int64_t n = 1; + /// If true (the default), null values are ignored. Otherwise, if any value is null, + /// emit null. + bool skip_nulls; + /// If less than this many non-null values are observed, emit null. + uint32_t min_count; +}; + +/// \brief Control Delta Degrees of Freedom (ddof) of Variance and Stddev kernel +/// +/// The divisor used in calculations is N - ddof, where N is the number of elements. +/// By default, ddof is zero, and population variance or stddev is returned. +class ARROW_EXPORT VarianceOptions : public FunctionOptions { + public: + explicit VarianceOptions(int ddof = 0, bool skip_nulls = true, uint32_t min_count = 0); + static constexpr const char kTypeName[] = "VarianceOptions"; + static VarianceOptions Defaults() { return VarianceOptions{}; } + + int ddof = 0; + /// If true (the default), null values are ignored. Otherwise, if any value is null, + /// emit null. + bool skip_nulls; + /// If less than this many non-null values are observed, emit null. + uint32_t min_count; +}; + +/// \brief Control Skew and Kurtosis kernel behavior +class ARROW_EXPORT SkewOptions : public FunctionOptions { + public: + explicit SkewOptions(bool skip_nulls = true, bool biased = true, + uint32_t min_count = 0); + static constexpr const char kTypeName[] = "SkewOptions"; + static SkewOptions Defaults() { return SkewOptions{}; } + + /// If true (the default), null values are ignored. Otherwise, if any value is null, + /// emit null. + bool skip_nulls; + /// If true (the default), the calculated value is biased. If false, the calculated + /// value includes a correction factor to reduce bias, making it more accurate for + /// small sample sizes. + bool biased; + /// If less than this many non-null values are observed, emit null. + uint32_t min_count; +}; + +/// \brief Control Quantile kernel behavior +/// +/// By default, returns the median value. +class ARROW_EXPORT QuantileOptions : public FunctionOptions { + public: + /// Interpolation method to use when quantile lies between two data points + enum Interpolation { + LINEAR = 0, + LOWER, + HIGHER, + NEAREST, + MIDPOINT, + }; + + explicit QuantileOptions(double q = 0.5, enum Interpolation interpolation = LINEAR, + bool skip_nulls = true, uint32_t min_count = 0); + + explicit QuantileOptions(std::vector q, + enum Interpolation interpolation = LINEAR, + bool skip_nulls = true, uint32_t min_count = 0); + + static constexpr const char kTypeName[] = "QuantileOptions"; + static QuantileOptions Defaults() { return QuantileOptions{}; } + + /// probability level of quantile must be between 0 and 1 inclusive + std::vector q; + enum Interpolation interpolation; + /// If true (the default), null values are ignored. Otherwise, if any value is null, + /// emit null. + bool skip_nulls; + /// If less than this many non-null values are observed, emit null. + uint32_t min_count; +}; + +/// \brief Control TDigest approximate quantile kernel behavior +/// +/// By default, returns the median value. +class ARROW_EXPORT TDigestOptions : public FunctionOptions { + public: + explicit TDigestOptions(double q = 0.5, uint32_t delta = 100, + uint32_t buffer_size = 500, bool skip_nulls = true, + uint32_t min_count = 0); + explicit TDigestOptions(std::vector q, uint32_t delta = 100, + uint32_t buffer_size = 500, bool skip_nulls = true, + uint32_t min_count = 0); + static constexpr const char kTypeName[] = "TDigestOptions"; + static TDigestOptions Defaults() { return TDigestOptions{}; } + + /// probability level of quantile must be between 0 and 1 inclusive + std::vector q; + /// compression parameter, default 100 + uint32_t delta; + /// input buffer size, default 500 + uint32_t buffer_size; + /// If true (the default), null values are ignored. Otherwise, if any value is null, + /// emit null. + bool skip_nulls; + /// If less than this many non-null values are observed, emit null. + uint32_t min_count; +}; + +/// \brief Control Pivot kernel behavior +/// +/// These options apply to the "pivot_wider" and "hash_pivot_wider" functions. +/// +/// Constraints: +/// - The corresponding `Aggregate::target` must have two FieldRef elements; +/// the first one points to the pivot key column, the second points to the +/// pivoted data column. +/// - The pivot key column can be string, binary or integer; its values will be +/// matched against `key_names` in order to dispatch the pivoted data into +/// the output. If the pivot key column is not string-like, the `key_names` +/// will be cast to the pivot key type. +/// +/// "pivot_wider" example +/// --------------------- +/// +/// Assuming the following two input columns with types utf8 and int16 (respectively): +/// ``` +/// width | 11 +/// height | 13 +/// ``` +/// and the options `PivotWiderOptions(.key_names = {"height", "width"})` +/// +/// then the output will be a scalar with the type +/// `struct{"height": int16, "width": int16}` +/// and the value `{"height": 13, "width": 11}`. +/// +/// "hash_pivot_wider" example +/// -------------------------- +/// +/// Assuming the following input with schema +/// `{"group": int32, "key": utf8, "value": int16}`: +/// ``` +/// group | key | value +/// ----------------------------- +/// 1 | height | 11 +/// 1 | width | 12 +/// 2 | width | 13 +/// 3 | height | 14 +/// 3 | depth | 15 +/// ``` +/// and the following settings: +/// - a hash grouping key "group" +/// - Aggregate( +/// .function = "hash_pivot_wider", +/// .options = PivotWiderOptions(.key_names = {"height", "width"}), +/// .target = {"key", "value"}, +/// .name = {"properties"}) +/// +/// then the output will have the schema +/// `{"group": int32, "properties": struct{"height": int16, "width": int16}}` +/// and the following value: +/// ``` +/// group | properties +/// | height | width +/// ----------------------------- +/// 1 | 11 | 12 +/// 2 | null | 13 +/// 3 | 14 | null +/// ``` +class ARROW_EXPORT PivotWiderOptions : public FunctionOptions { + public: + /// Configure the behavior of pivot keys not in `key_names` + enum UnexpectedKeyBehavior { + /// Unexpected pivot keys are ignored silently + kIgnore, + /// Unexpected pivot keys return a KeyError + kRaise + }; + + explicit PivotWiderOptions(std::vector key_names, + UnexpectedKeyBehavior unexpected_key_behavior = kIgnore); + // Default constructor for serialization + PivotWiderOptions(); + static constexpr const char kTypeName[] = "PivotWiderOptions"; + static PivotWiderOptions Defaults() { return PivotWiderOptions{}; } + + /// The values expected in the pivot key column + std::vector key_names; + /// The behavior when pivot keys not in `key_names` are encountered + UnexpectedKeyBehavior unexpected_key_behavior = kIgnore; +}; + +/// \brief Control Index kernel behavior +class ARROW_EXPORT IndexOptions : public FunctionOptions { + public: + explicit IndexOptions(std::shared_ptr value); + // Default constructor for serialization + IndexOptions(); + static constexpr const char kTypeName[] = "IndexOptions"; + + std::shared_ptr value; +}; + +/// \brief Configure a grouped aggregation +struct ARROW_EXPORT Aggregate { + Aggregate() = default; + + Aggregate(std::string function, std::shared_ptr options, + std::vector target, std::string name = "") + : function(std::move(function)), + options(std::move(options)), + target(std::move(target)), + name(std::move(name)) {} + + Aggregate(std::string function, std::shared_ptr options, + FieldRef target, std::string name = "") + : Aggregate(std::move(function), std::move(options), + std::vector{std::move(target)}, std::move(name)) {} + + Aggregate(std::string function, FieldRef target, std::string name) + : Aggregate(std::move(function), /*options=*/NULLPTR, + std::vector{std::move(target)}, std::move(name)) {} + + Aggregate(std::string function, std::string name) + : Aggregate(std::move(function), /*options=*/NULLPTR, + /*target=*/std::vector{}, std::move(name)) {} + + /// the name of the aggregation function + std::string function; + + /// options for the aggregation function + std::shared_ptr options; + + /// zero or more fields to which aggregations will be applied + std::vector target; + + /// optional output field name for aggregations + std::string name; +}; + +/// @} + +/// \brief Count values in an array. +/// +/// \param[in] options counting options, see CountOptions for more information +/// \param[in] datum to count +/// \param[in] ctx the function execution context, optional +/// \return out resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Count(const Datum& datum, + const CountOptions& options = CountOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the mean of a numeric array. +/// +/// \param[in] value datum to compute the mean, expecting Array +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed mean as a DoubleScalar +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Mean( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the product of values of a numeric array. +/// +/// \param[in] value datum to compute product of, expecting Array or ChunkedArray +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed sum as a Scalar +/// +/// \since 6.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Product( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Sum values of a numeric array. +/// +/// \param[in] value datum to sum, expecting Array or ChunkedArray +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed sum as a Scalar +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Sum( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the first value of an array +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed first as Scalar +/// +/// \since 13.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result First( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the last value of an array +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed last as a Scalar +/// +/// \since 13.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Last( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the min / max of a numeric array +/// +/// This function returns both the min and max as a struct scalar, with type +/// struct, where T is the input type +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return resulting datum as a struct scalar +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result MinMax( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Test whether any element in a boolean array evaluates to true. +/// +/// This function returns true if any of the elements in the array evaluates +/// to true and false otherwise. Null values are ignored by default. +/// If null values are taken into account by setting ScalarAggregateOptions +/// parameter skip_nulls = false then Kleene logic is used. +/// See KleeneOr for more details on Kleene logic. +/// +/// \param[in] value input datum, expecting a boolean array +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return resulting datum as a BooleanScalar +/// +/// \since 3.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Any( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Test whether all elements in a boolean array evaluate to true. +/// +/// This function returns true if all of the elements in the array evaluate +/// to true and false otherwise. Null values are ignored by default. +/// If null values are taken into account by setting ScalarAggregateOptions +/// parameter skip_nulls = false then Kleene logic is used. +/// See KleeneAnd for more details on Kleene logic. +/// +/// \param[in] value input datum, expecting a boolean array +/// \param[in] options see ScalarAggregateOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return resulting datum as a BooleanScalar + +/// \since 3.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result All( + const Datum& value, + const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the modal (most common) value of a numeric array +/// +/// This function returns top-n most common values and number of times they occur as +/// an array of `struct`, where T is the input type. +/// Values with larger counts are returned before smaller ones. +/// If there are more than one values with same count, smaller value is returned first. +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see ModeOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return resulting datum as an array of struct +/// +/// \since 2.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Mode(const Datum& value, + const ModeOptions& options = ModeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the standard deviation of a numeric array +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see VarianceOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed standard deviation as a DoubleScalar +/// +/// \since 2.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Stddev(const Datum& value, + const VarianceOptions& options = VarianceOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the variance of a numeric array +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see VarianceOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed variance as a DoubleScalar +/// +/// \since 2.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Variance(const Datum& value, + const VarianceOptions& options = VarianceOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the skewness of a numeric array +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see SkewOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed skewness as a DoubleScalar +/// +/// \since 20.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Skew(const Datum& value, + const SkewOptions& options = SkewOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the kurtosis of a numeric array +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see SkewOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return datum of the computed kurtosis as a DoubleScalar +/// +/// \since 20.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Kurtosis(const Datum& value, + const SkewOptions& options = SkewOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the quantiles of a numeric array +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see QuantileOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return resulting datum as an array +/// +/// \since 4.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Quantile(const Datum& value, + const QuantileOptions& options = QuantileOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Calculate the approximate quantiles of a numeric array with T-Digest algorithm +/// +/// \param[in] value input datum, expecting Array or ChunkedArray +/// \param[in] options see TDigestOptions for more information +/// \param[in] ctx the function execution context, optional +/// \return resulting datum as an array +/// +/// \since 4.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result TDigest(const Datum& value, + const TDigestOptions& options = TDigestOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Find the first index of a value in an array. +/// +/// \param[in] value The array to search. +/// \param[in] options The array to search for. See IndexOptions. +/// \param[in] ctx the function execution context, optional +/// \return out a Scalar containing the index (or -1 if not found). +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Index(const Datum& value, const IndexOptions& options, + ExecContext* ctx = NULLPTR); + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_scalar.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_scalar.h new file mode 100644 index 0000000000000000000000000000000000000000..8b341e865a1665ee18229d0b78ad1aaf2d778325 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_scalar.h @@ -0,0 +1,1802 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Eager evaluation convenience APIs for invoking common functions, including +// necessary memory allocations + +#pragma once + +#include +#include +#include + +#include "arrow/compute/function_options.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/datum.h" +#include "arrow/result.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace compute { + +/// \addtogroup compute-concrete-options +/// +/// @{ + +class ARROW_EXPORT ArithmeticOptions : public FunctionOptions { + public: + explicit ArithmeticOptions(bool check_overflow = false); + static constexpr const char kTypeName[] = "ArithmeticOptions"; + bool check_overflow; +}; + +class ARROW_EXPORT ElementWiseAggregateOptions : public FunctionOptions { + public: + explicit ElementWiseAggregateOptions(bool skip_nulls = true); + static constexpr const char kTypeName[] = "ElementWiseAggregateOptions"; + static ElementWiseAggregateOptions Defaults() { return ElementWiseAggregateOptions{}; } + bool skip_nulls; +}; + +/// Rounding and tie-breaking modes for round compute functions. +/// Additional details and examples are provided in compute.rst. +enum class RoundMode : int8_t { + /// Round to nearest integer less than or equal in magnitude (aka "floor") + DOWN, + /// Round to nearest integer greater than or equal in magnitude (aka "ceil") + UP, + /// Get the integral part without fractional digits (aka "trunc") + TOWARDS_ZERO, + /// Round negative values with DOWN rule + /// and positive values with UP rule (aka "away from zero") + TOWARDS_INFINITY, + /// Round ties with DOWN rule (also called "round half towards negative infinity") + HALF_DOWN, + /// Round ties with UP rule (also called "round half towards positive infinity") + HALF_UP, + /// Round ties with TOWARDS_ZERO rule (also called "round half away from infinity") + HALF_TOWARDS_ZERO, + /// Round ties with TOWARDS_INFINITY rule (also called "round half away from zero") + HALF_TOWARDS_INFINITY, + /// Round ties to nearest even integer + HALF_TO_EVEN, + /// Round ties to nearest odd integer + HALF_TO_ODD, +}; + +class ARROW_EXPORT RoundOptions : public FunctionOptions { + public: + explicit RoundOptions(int64_t ndigits = 0, + RoundMode round_mode = RoundMode::HALF_TO_EVEN); + static constexpr const char kTypeName[] = "RoundOptions"; + static RoundOptions Defaults() { return RoundOptions(); } + /// Rounding precision (number of digits to round to) + int64_t ndigits; + /// Rounding and tie-breaking mode + RoundMode round_mode; +}; + +class ARROW_EXPORT RoundBinaryOptions : public FunctionOptions { + public: + explicit RoundBinaryOptions(RoundMode round_mode = RoundMode::HALF_TO_EVEN); + static constexpr const char kTypeName[] = "RoundBinaryOptions"; + static RoundBinaryOptions Defaults() { return RoundBinaryOptions(); } + /// Rounding and tie-breaking mode + RoundMode round_mode; +}; + +enum class CalendarUnit : int8_t { + NANOSECOND, + MICROSECOND, + MILLISECOND, + SECOND, + MINUTE, + HOUR, + DAY, + WEEK, + MONTH, + QUARTER, + YEAR +}; + +class ARROW_EXPORT RoundTemporalOptions : public FunctionOptions { + public: + explicit RoundTemporalOptions(int multiple = 1, CalendarUnit unit = CalendarUnit::DAY, + bool week_starts_monday = true, + bool ceil_is_strictly_greater = false, + bool calendar_based_origin = false); + static constexpr const char kTypeName[] = "RoundTemporalOptions"; + static RoundTemporalOptions Defaults() { return RoundTemporalOptions(); } + + /// Number of units to round to + int multiple; + /// The unit used for rounding of time + CalendarUnit unit; + /// What day does the week start with (Monday=true, Sunday=false) + bool week_starts_monday; + /// Enable this flag to return a rounded value that is strictly greater than the input. + /// For example: ceiling 1970-01-01T00:00:00 to 3 hours would yield 1970-01-01T03:00:00 + /// if set to true and 1970-01-01T00:00:00 if set to false. + /// This applies for ceiling only. + bool ceil_is_strictly_greater; + /// By default time is rounded to a multiple of units since 1970-01-01T00:00:00. + /// By setting calendar_based_origin to true, time will be rounded to a number + /// of units since the last greater calendar unit. + /// For example: rounding to a multiple of days since the beginning of the month or + /// to hours since the beginning of the day. + /// Exceptions: week and quarter are not used as greater units, therefore days will + /// will be rounded to the beginning of the month not week. Greater unit of week + /// is year. + /// Note that ceiling and rounding might change sorting order of an array near greater + /// unit change. For example rounding YYYY-mm-dd 23:00:00 to 5 hours will ceil and + /// round to YYYY-mm-dd+1 01:00:00 and floor to YYYY-mm-dd 20:00:00. On the other hand + /// YYYY-mm-dd+1 00:00:00 will ceil, round and floor to YYYY-mm-dd+1 00:00:00. This + /// can break the order of an already ordered array. + bool calendar_based_origin; +}; + +class ARROW_EXPORT RoundToMultipleOptions : public FunctionOptions { + public: + explicit RoundToMultipleOptions(double multiple = 1.0, + RoundMode round_mode = RoundMode::HALF_TO_EVEN); + explicit RoundToMultipleOptions(std::shared_ptr multiple, + RoundMode round_mode = RoundMode::HALF_TO_EVEN); + static constexpr const char kTypeName[] = "RoundToMultipleOptions"; + static RoundToMultipleOptions Defaults() { return RoundToMultipleOptions(); } + /// Rounding scale (multiple to round to). + /// + /// Should be a positive numeric scalar of a type compatible with the + /// argument to be rounded. The cast kernel is used to convert the rounding + /// multiple to match the result type. + std::shared_ptr multiple; + /// Rounding and tie-breaking mode + RoundMode round_mode; +}; + +/// Options for var_args_join. +class ARROW_EXPORT JoinOptions : public FunctionOptions { + public: + /// How to handle null values. (A null separator always results in a null output.) + enum NullHandlingBehavior { + /// A null in any input results in a null in the output. + EMIT_NULL, + /// Nulls in inputs are skipped. + SKIP, + /// Nulls in inputs are replaced with the replacement string. + REPLACE, + }; + explicit JoinOptions(NullHandlingBehavior null_handling = EMIT_NULL, + std::string null_replacement = ""); + static constexpr const char kTypeName[] = "JoinOptions"; + static JoinOptions Defaults() { return JoinOptions(); } + NullHandlingBehavior null_handling; + std::string null_replacement; +}; + +class ARROW_EXPORT MatchSubstringOptions : public FunctionOptions { + public: + explicit MatchSubstringOptions(std::string pattern, bool ignore_case = false); + MatchSubstringOptions(); + static constexpr const char kTypeName[] = "MatchSubstringOptions"; + + /// The exact substring (or regex, depending on kernel) to look for inside input values. + std::string pattern; + /// Whether to perform a case-insensitive match. + bool ignore_case; +}; + +class ARROW_EXPORT SplitOptions : public FunctionOptions { + public: + explicit SplitOptions(int64_t max_splits = -1, bool reverse = false); + static constexpr const char kTypeName[] = "SplitOptions"; + + /// Maximum number of splits allowed, or unlimited when -1 + int64_t max_splits; + /// Start splitting from the end of the string (only relevant when max_splits != -1) + bool reverse; +}; + +class ARROW_EXPORT SplitPatternOptions : public FunctionOptions { + public: + explicit SplitPatternOptions(std::string pattern, int64_t max_splits = -1, + bool reverse = false); + SplitPatternOptions(); + static constexpr const char kTypeName[] = "SplitPatternOptions"; + + /// The exact substring to split on. + std::string pattern; + /// Maximum number of splits allowed, or unlimited when -1 + int64_t max_splits; + /// Start splitting from the end of the string (only relevant when max_splits != -1) + bool reverse; +}; + +class ARROW_EXPORT ReplaceSliceOptions : public FunctionOptions { + public: + explicit ReplaceSliceOptions(int64_t start, int64_t stop, std::string replacement); + ReplaceSliceOptions(); + static constexpr const char kTypeName[] = "ReplaceSliceOptions"; + + /// Index to start slicing at + int64_t start; + /// Index to stop slicing at + int64_t stop; + /// String to replace the slice with + std::string replacement; +}; + +class ARROW_EXPORT ReplaceSubstringOptions : public FunctionOptions { + public: + explicit ReplaceSubstringOptions(std::string pattern, std::string replacement, + int64_t max_replacements = -1); + ReplaceSubstringOptions(); + static constexpr const char kTypeName[] = "ReplaceSubstringOptions"; + + /// Pattern to match, literal, or regular expression depending on which kernel is used + std::string pattern; + /// String to replace the pattern with + std::string replacement; + /// Max number of substrings to replace (-1 means unbounded) + int64_t max_replacements; +}; + +class ARROW_EXPORT ExtractRegexOptions : public FunctionOptions { + public: + explicit ExtractRegexOptions(std::string pattern); + ExtractRegexOptions(); + static constexpr const char kTypeName[] = "ExtractRegexOptions"; + + /// Regular expression with named capture fields + std::string pattern; +}; + +class ARROW_EXPORT ExtractRegexSpanOptions : public FunctionOptions { + public: + explicit ExtractRegexSpanOptions(std::string pattern); + ExtractRegexSpanOptions(); + static constexpr const char kTypeName[] = "ExtractRegexSpanOptions"; + + /// Regular expression with named capture fields + std::string pattern; +}; + +/// Options for IsIn and IndexIn functions +class ARROW_EXPORT SetLookupOptions : public FunctionOptions { + public: + /// How to handle null values. + enum NullMatchingBehavior { + /// MATCH, any null in `value_set` is successfully matched in + /// the input. + MATCH, + /// SKIP, any null in `value_set` is ignored and nulls in the input + /// produce null (IndexIn) or false (IsIn) values in the output. + SKIP, + /// EMIT_NULL, any null in `value_set` is ignored and nulls in the + /// input produce null (IndexIn and IsIn) values in the output. + EMIT_NULL, + /// INCONCLUSIVE, null values are regarded as unknown values, which is + /// sql-compatible. nulls in the input produce null (IndexIn and IsIn) + /// values in the output. Besides, if `value_set` contains a null, + /// non-null unmatched values in the input also produce null values + /// (IndexIn and IsIn) in the output. + INCONCLUSIVE + }; + + explicit SetLookupOptions(Datum value_set, NullMatchingBehavior = MATCH); + SetLookupOptions(); + + // DEPRECATED(will be removed after removing of skip_nulls) + explicit SetLookupOptions(Datum value_set, bool skip_nulls); + + static constexpr const char kTypeName[] = "SetLookupOptions"; + + /// The set of values to look up input values into. + Datum value_set; + + NullMatchingBehavior null_matching_behavior; + + // DEPRECATED(will be removed after removing of skip_nulls) + NullMatchingBehavior GetNullMatchingBehavior() const; + + // DEPRECATED(use null_matching_behavior instead) + /// Whether nulls in `value_set` count for lookup. + /// + /// If true, any null in `value_set` is ignored and nulls in the input + /// produce null (IndexIn) or false (IsIn) values in the output. + /// If false, any null in `value_set` is successfully matched in + /// the input. + std::optional skip_nulls; +}; + +/// Options for struct_field function +class ARROW_EXPORT StructFieldOptions : public FunctionOptions { + public: + explicit StructFieldOptions(std::vector indices); + explicit StructFieldOptions(std::initializer_list); + explicit StructFieldOptions(FieldRef field_ref); + StructFieldOptions(); + static constexpr const char kTypeName[] = "StructFieldOptions"; + + /// The FieldRef specifying what to extract from struct or union. + FieldRef field_ref; +}; + +class ARROW_EXPORT StrptimeOptions : public FunctionOptions { + public: + explicit StrptimeOptions(std::string format, TimeUnit::type unit, + bool error_is_null = false); + StrptimeOptions(); + static constexpr const char kTypeName[] = "StrptimeOptions"; + + /// The desired format string. + std::string format; + /// The desired time resolution + TimeUnit::type unit; + /// Return null on parsing errors if true or raise if false + bool error_is_null; +}; + +class ARROW_EXPORT StrftimeOptions : public FunctionOptions { + public: + explicit StrftimeOptions(std::string format, std::string locale = "C"); + StrftimeOptions(); + + static constexpr const char kTypeName[] = "StrftimeOptions"; + + static constexpr const char* kDefaultFormat = "%Y-%m-%dT%H:%M:%S"; + + /// The desired format string. + std::string format; + /// The desired output locale string. + std::string locale; +}; + +class ARROW_EXPORT PadOptions : public FunctionOptions { + public: + explicit PadOptions(int64_t width, std::string padding = " ", + bool lean_left_on_odd_padding = true); + PadOptions(); + static constexpr const char kTypeName[] = "PadOptions"; + + /// The desired string length. + int64_t width; + /// What to pad the string with. Should be one codepoint (Unicode)/byte (ASCII). + std::string padding; + /// What to do if there is an odd number of padding characters (in case of centered + /// padding). Defaults to aligning on the left (i.e. adding the extra padding character + /// on the right) + bool lean_left_on_odd_padding = true; +}; + +class ARROW_EXPORT ZeroFillOptions : public FunctionOptions { + public: + explicit ZeroFillOptions(int64_t width, std::string padding = "0"); + ZeroFillOptions(); + static constexpr const char kTypeName[] = "ZeroFillOptions"; + + /// The desired string length. + int64_t width; + /// What to pad the string with. Should be one codepoint (Unicode). + std::string padding; +}; + +class ARROW_EXPORT TrimOptions : public FunctionOptions { + public: + explicit TrimOptions(std::string characters); + TrimOptions(); + static constexpr const char kTypeName[] = "TrimOptions"; + + /// The individual characters to be trimmed from the string. + std::string characters; +}; + +class ARROW_EXPORT SliceOptions : public FunctionOptions { + public: + explicit SliceOptions(int64_t start, int64_t stop = std::numeric_limits::max(), + int64_t step = 1); + SliceOptions(); + static constexpr const char kTypeName[] = "SliceOptions"; + int64_t start, stop, step; +}; + +class ARROW_EXPORT ListSliceOptions : public FunctionOptions { + public: + explicit ListSliceOptions(int64_t start, std::optional stop = std::nullopt, + int64_t step = 1, + std::optional return_fixed_size_list = std::nullopt); + ListSliceOptions(); + static constexpr const char kTypeName[] = "ListSliceOptions"; + /// The start of list slicing. + int64_t start; + /// Optional stop of list slicing. If not set, then slice to end. (NotImplemented) + std::optional stop; + /// Slicing step + int64_t step; + // Whether to return a FixedSizeListArray. If true _and_ stop is after + // a list element's length, nulls will be appended to create the requested slice size. + // Default of `nullopt` will return whatever type it got in. + std::optional return_fixed_size_list; +}; + +class ARROW_EXPORT NullOptions : public FunctionOptions { + public: + explicit NullOptions(bool nan_is_null = false); + static constexpr const char kTypeName[] = "NullOptions"; + static NullOptions Defaults() { return NullOptions{}; } + + bool nan_is_null; +}; + +enum CompareOperator : int8_t { + EQUAL, + NOT_EQUAL, + GREATER, + GREATER_EQUAL, + LESS, + LESS_EQUAL, +}; + +struct ARROW_EXPORT CompareOptions { + explicit CompareOptions(CompareOperator op) : op(op) {} + CompareOptions() : CompareOptions(CompareOperator::EQUAL) {} + enum CompareOperator op; +}; + +class ARROW_EXPORT MakeStructOptions : public FunctionOptions { + public: + MakeStructOptions(std::vector n, std::vector r, + std::vector> m); + explicit MakeStructOptions(std::vector n); + MakeStructOptions(); + static constexpr const char kTypeName[] = "MakeStructOptions"; + + /// Names for wrapped columns + std::vector field_names; + + /// Nullability bits for wrapped columns + std::vector field_nullability; + + /// Metadata attached to wrapped columns + std::vector> field_metadata; +}; + +struct ARROW_EXPORT DayOfWeekOptions : public FunctionOptions { + public: + explicit DayOfWeekOptions(bool count_from_zero = true, uint32_t week_start = 1); + static constexpr const char kTypeName[] = "DayOfWeekOptions"; + static DayOfWeekOptions Defaults() { return DayOfWeekOptions(); } + + /// Number days from 0 if true and from 1 if false + bool count_from_zero; + /// What day does the week start with (Monday=1, Sunday=7). + /// The numbering is unaffected by the count_from_zero parameter. + uint32_t week_start; +}; + +/// Used to control timestamp timezone conversion and handling ambiguous/nonexistent +/// times. +struct ARROW_EXPORT AssumeTimezoneOptions : public FunctionOptions { + public: + /// \brief How to interpret ambiguous local times that can be interpreted as + /// multiple instants (normally two) due to DST shifts. + /// + /// AMBIGUOUS_EARLIEST emits the earliest instant amongst possible interpretations. + /// AMBIGUOUS_LATEST emits the latest instant amongst possible interpretations. + enum Ambiguous { AMBIGUOUS_RAISE, AMBIGUOUS_EARLIEST, AMBIGUOUS_LATEST }; + + /// \brief How to handle local times that do not exist due to DST shifts. + /// + /// NONEXISTENT_EARLIEST emits the instant "just before" the DST shift instant + /// in the given timestamp precision (for example, for a nanoseconds precision + /// timestamp, this is one nanosecond before the DST shift instant). + /// NONEXISTENT_LATEST emits the DST shift instant. + enum Nonexistent { NONEXISTENT_RAISE, NONEXISTENT_EARLIEST, NONEXISTENT_LATEST }; + + explicit AssumeTimezoneOptions(std::string timezone, + Ambiguous ambiguous = AMBIGUOUS_RAISE, + Nonexistent nonexistent = NONEXISTENT_RAISE); + AssumeTimezoneOptions(); + static constexpr const char kTypeName[] = "AssumeTimezoneOptions"; + + /// Timezone to convert timestamps from + std::string timezone; + + /// How to interpret ambiguous local times (due to DST shifts) + Ambiguous ambiguous; + /// How to interpret nonexistent local times (due to DST shifts) + Nonexistent nonexistent; +}; + +struct ARROW_EXPORT WeekOptions : public FunctionOptions { + public: + explicit WeekOptions(bool week_starts_monday = true, bool count_from_zero = false, + bool first_week_is_fully_in_year = false); + static constexpr const char kTypeName[] = "WeekOptions"; + static WeekOptions Defaults() { return WeekOptions{}; } + static WeekOptions ISODefaults() { + return WeekOptions{/*week_starts_monday*/ true, + /*count_from_zero=*/false, + /*first_week_is_fully_in_year=*/false}; + } + static WeekOptions USDefaults() { + return WeekOptions{/*week_starts_monday*/ false, + /*count_from_zero=*/false, + /*first_week_is_fully_in_year=*/false}; + } + + /// What day does the week start with (Monday=true, Sunday=false) + bool week_starts_monday; + /// Dates from current year that fall into last ISO week of the previous year return + /// 0 if true and 52 or 53 if false. + bool count_from_zero; + /// Must the first week be fully in January (true), or is a week that begins on + /// December 29, 30, or 31 considered to be the first week of the new year (false)? + bool first_week_is_fully_in_year; +}; + +struct ARROW_EXPORT Utf8NormalizeOptions : public FunctionOptions { + public: + enum Form { NFC, NFKC, NFD, NFKD }; + + explicit Utf8NormalizeOptions(Form form = NFC); + static Utf8NormalizeOptions Defaults() { return Utf8NormalizeOptions(); } + static constexpr const char kTypeName[] = "Utf8NormalizeOptions"; + + /// The Unicode normalization form to apply + Form form; +}; + +class ARROW_EXPORT RandomOptions : public FunctionOptions { + public: + enum Initializer { SystemRandom, Seed }; + + static RandomOptions FromSystemRandom() { return RandomOptions{SystemRandom, 0}; } + static RandomOptions FromSeed(uint64_t seed) { return RandomOptions{Seed, seed}; } + + RandomOptions(Initializer initializer, uint64_t seed); + RandomOptions(); + static constexpr const char kTypeName[] = "RandomOptions"; + static RandomOptions Defaults() { return RandomOptions(); } + + /// The type of initialization for random number generation - system or provided seed. + Initializer initializer; + /// The seed value used to initialize the random number generation. + uint64_t seed; +}; + +/// Options for map_lookup function +class ARROW_EXPORT MapLookupOptions : public FunctionOptions { + public: + enum Occurrence { + /// Return the first matching value + FIRST, + /// Return the last matching value + LAST, + /// Return all matching values + ALL + }; + + explicit MapLookupOptions(std::shared_ptr query_key, Occurrence occurrence); + MapLookupOptions(); + + constexpr static const char kTypeName[] = "MapLookupOptions"; + + /// The key to lookup in the map + std::shared_ptr query_key; + + /// Whether to return the first, last, or all matching values + Occurrence occurrence; +}; + +/// @} + +/// \brief Get the absolute value of a value. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the value transformed +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise absolute value +ARROW_EXPORT +Result AbsoluteValue(const Datum& arg, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Add two values together. Array values must be the same length. If +/// either addend is null the result will be null. +/// +/// \param[in] left the first addend +/// \param[in] right the second addend +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise sum +ARROW_EXPORT +Result Add(const Datum& left, const Datum& right, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Subtract two values. Array values must be the same length. If the +/// minuend or subtrahend is null the result will be null. +/// +/// \param[in] left the value subtracted from (minuend) +/// \param[in] right the value by which the minuend is reduced (subtrahend) +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise difference +ARROW_EXPORT +Result Subtract(const Datum& left, const Datum& right, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Multiply two values. Array values must be the same length. If either +/// factor is null the result will be null. +/// +/// \param[in] left the first factor +/// \param[in] right the second factor +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise product +ARROW_EXPORT +Result Multiply(const Datum& left, const Datum& right, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Divide two values. Array values must be the same length. If either +/// argument is null the result will be null. For integer types, if there is +/// a zero divisor, an error will be raised. +/// +/// \param[in] left the dividend +/// \param[in] right the divisor +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise quotient +ARROW_EXPORT +Result Divide(const Datum& left, const Datum& right, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Negate values. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the value negated +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise negation +ARROW_EXPORT +Result Negate(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Raise the values of base array to the power of the exponent array values. +/// Array values must be the same length. If either base or exponent is null the result +/// will be null. +/// +/// \param[in] left the base +/// \param[in] right the exponent +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise base value raised to the power of exponent +ARROW_EXPORT +Result Power(const Datum& left, const Datum& right, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Raise Euler's number to the power of specified exponent, element-wise. +/// If the exponent value is null the result will be null. +/// +/// \param[in] arg the exponent +/// \param[in] ctx the function execution context, optional +/// \return the element-wise Euler's number raised to the power of exponent +ARROW_EXPORT +Result Exp(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief More accurately calculate `exp(arg) - 1` for values close to zero. +/// If the exponent value is null the result will be null. +/// +/// This function is more accurate than calculating `exp(value) - 1` directly for values +/// close to zero. +/// +/// \param[in] arg the exponent +/// \param[in] ctx the function execution context, optional +/// \return the element-wise Euler's number raised to the power of exponent minus 1 +ARROW_EXPORT +Result Expm1(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Left shift the left array by the right array. Array values must be the +/// same length. If either operand is null, the result will be null. +/// +/// \param[in] left the value to shift +/// \param[in] right the value to shift by +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise left value shifted left by the right value +ARROW_EXPORT +Result ShiftLeft(const Datum& left, const Datum& right, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Right shift the left array by the right array. Array values must be the +/// same length. If either operand is null, the result will be null. Performs a +/// logical shift for unsigned values, and an arithmetic shift for signed values. +/// +/// \param[in] left the value to shift +/// \param[in] right the value to shift by +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise left value shifted right by the right value +ARROW_EXPORT +Result ShiftRight(const Datum& left, const Datum& right, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the sine of the array values. +/// \param[in] arg The values to compute the sine for. +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise sine of the values +ARROW_EXPORT +Result Sin(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the cosine of the array values. +/// \param[in] arg The values to compute the cosine for. +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise cosine of the values +ARROW_EXPORT +Result Cos(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the inverse sine (arcsine) of the array values. +/// \param[in] arg The values to compute the inverse sine for. +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise inverse sine of the values +ARROW_EXPORT +Result Asin(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the inverse cosine (arccosine) of the array values. +/// \param[in] arg The values to compute the inverse cosine for. +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise inverse cosine of the values +ARROW_EXPORT +Result Acos(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the tangent of the array values. +/// \param[in] arg The values to compute the tangent for. +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise tangent of the values +ARROW_EXPORT +Result Tan(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the inverse tangent (arctangent) of the array values. +/// \param[in] arg The values to compute the inverse tangent for. +/// \param[in] ctx the function execution context, optional +/// \return the elementwise inverse tangent of the values +ARROW_EXPORT +Result Atan(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Compute the inverse tangent (arctangent) of y/x, using the +/// argument signs to determine the correct quadrant. +/// \param[in] y The y-values to compute the inverse tangent for. +/// \param[in] x The x-values to compute the inverse tangent for. +/// \param[in] ctx the function execution context, optional +/// \return the elementwise inverse tangent of the values +ARROW_EXPORT +Result Atan2(const Datum& y, const Datum& x, ExecContext* ctx = NULLPTR); + +/// \brief Compute the hyperbolic sine of the array values. +/// \param[in] arg The values to compute the hyperbolic sine for. +/// \param[in] ctx the function execution context, optional +/// \return the elementwise hyperbolic sine of the values +ARROW_EXPORT +Result Sinh(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Compute the hyperbolic cosine of the array values. +/// \param[in] arg The values to compute the hyperbolic cosine for. +/// \param[in] ctx the function execution context, optional +/// \return the elementwise hyperbolic cosine of the values +ARROW_EXPORT +Result Cosh(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Compute the hyperbolic tangent of the array values. +/// \param[in] arg The values to compute the hyperbolic tangent for. +/// \param[in] ctx the function execution context, optional +/// \return the elementwise hyperbolic tangent of the values +ARROW_EXPORT +Result Tanh(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Compute the inverse hyperbolic sine of the array values. +/// \param[in] arg The values to compute the inverse hyperbolic sine for. +/// \param[in] ctx the function execution context, optional +/// \return the elementwise inverse hyperbolic sine of the values +ARROW_EXPORT +Result Asinh(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Compute the inverse hyperbolic cosine of the array values. +/// \param[in] arg The values to compute the inverse hyperbolic cosine for. +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise inverse hyperbolic cosine of the values +ARROW_EXPORT +Result Acosh(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the inverse hyperbolic tangent of the array values. +/// \param[in] arg The values to compute the inverse hyperbolic tangent for. +/// \param[in] options arithmetic options (enable/disable overflow checking), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise inverse hyperbolic tangent of the values +ARROW_EXPORT +Result Atanh(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Get the natural log of a value. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg The values to compute the logarithm for. +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise natural log +ARROW_EXPORT +Result Ln(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Get the log base 10 of a value. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg The values to compute the logarithm for. +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise log base 10 +ARROW_EXPORT +Result Log10(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Get the log base 2 of a value. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg The values to compute the logarithm for. +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise log base 2 +ARROW_EXPORT +Result Log2(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Get the natural log of (1 + value). +/// +/// If argument is null the result will be null. +/// This function may be more accurate than Log(1 + value) for values close to zero. +/// +/// \param[in] arg The values to compute the logarithm for. +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise natural log +ARROW_EXPORT +Result Log1p(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Get the log of a value to the given base. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg The values to compute the logarithm for. +/// \param[in] base The given base. +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise log to the given base +ARROW_EXPORT +Result Logb(const Datum& arg, const Datum& base, + ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Get the square-root of a value. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg The values to compute the square-root for. +/// \param[in] options arithmetic options (overflow handling), optional +/// \param[in] ctx the function execution context, optional +/// \return the elementwise square-root +ARROW_EXPORT +Result Sqrt(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief Round to the nearest integer less than or equal in magnitude to the +/// argument. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the value to round +/// \param[in] ctx the function execution context, optional +/// \return the rounded value +ARROW_EXPORT +Result Floor(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Round to the nearest integer greater than or equal in magnitude to the +/// argument. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the value to round +/// \param[in] ctx the function execution context, optional +/// \return the rounded value +ARROW_EXPORT +Result Ceil(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Get the integral part without fractional digits. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the value to truncate +/// \param[in] ctx the function execution context, optional +/// \return the truncated value +ARROW_EXPORT +Result Trunc(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Find the element-wise maximum of any number of arrays or scalars. +/// Array values must be the same length. +/// +/// \param[in] args arrays or scalars to operate on. +/// \param[in] options options for handling nulls, optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise maximum +ARROW_EXPORT +Result MaxElementWise( + const std::vector& args, + ElementWiseAggregateOptions options = ElementWiseAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Find the element-wise minimum of any number of arrays or scalars. +/// Array values must be the same length. +/// +/// \param[in] args arrays or scalars to operate on. +/// \param[in] options options for handling nulls, optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise minimum +ARROW_EXPORT +Result MinElementWise( + const std::vector& args, + ElementWiseAggregateOptions options = ElementWiseAggregateOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Get the sign of a value. Array values can be of arbitrary length. If argument +/// is null the result will be null. +/// +/// \param[in] arg the value to extract sign from +/// \param[in] ctx the function execution context, optional +/// \return the element-wise sign function +ARROW_EXPORT +Result Sign(const Datum& arg, ExecContext* ctx = NULLPTR); + +/// \brief Round a value to a given precision. +/// +/// If arg is null the result will be null. +/// +/// \param[in] arg the value to be rounded +/// \param[in] options rounding options (rounding mode and number of digits), optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise rounded value +ARROW_EXPORT +Result Round(const Datum& arg, RoundOptions options = RoundOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Round a value to a given precision. +/// +/// If arg1 is null the result will be null. +/// If arg2 is null then the result will be null. If arg2 is negative, then the rounding +/// place will be shifted to the left (thus -1 would correspond to rounding to the nearest +/// ten). If positive, the rounding place will shift to the right (and +1 would +/// correspond to rounding to the nearest tenth). +/// +/// \param[in] arg1 the value to be rounded +/// \param[in] arg2 the number of significant digits to round to +/// \param[in] options rounding options, optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise rounded value +ARROW_EXPORT +Result RoundBinary(const Datum& arg1, const Datum& arg2, + RoundBinaryOptions options = RoundBinaryOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Round a value to a given multiple. +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the value to round +/// \param[in] options rounding options (rounding mode and multiple), optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise rounded value +ARROW_EXPORT +Result RoundToMultiple( + const Datum& arg, RoundToMultipleOptions options = RoundToMultipleOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Ceil a temporal value to a given frequency +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the temporal value to ceil +/// \param[in] options temporal rounding options, optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise rounded value +/// +/// \since 7.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result CeilTemporal( + const Datum& arg, RoundTemporalOptions options = RoundTemporalOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Floor a temporal value to a given frequency +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the temporal value to floor +/// \param[in] options temporal rounding options, optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise rounded value +/// +/// \since 7.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result FloorTemporal( + const Datum& arg, RoundTemporalOptions options = RoundTemporalOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Round a temporal value to a given frequency +/// +/// If argument is null the result will be null. +/// +/// \param[in] arg the temporal value to round +/// \param[in] options temporal rounding options, optional +/// \param[in] ctx the function execution context, optional +/// \return the element-wise rounded value +/// +/// \since 7.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result RoundTemporal( + const Datum& arg, RoundTemporalOptions options = RoundTemporalOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Invert the values of a boolean datum +/// \param[in] value datum to invert +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Invert(const Datum& value, ExecContext* ctx = NULLPTR); + +/// \brief Element-wise AND of two boolean datums which always propagates nulls +/// (null and false is null). +/// +/// \param[in] left left operand +/// \param[in] right right operand +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result And(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR); + +/// \brief Element-wise AND of two boolean datums with a Kleene truth table +/// (null and false is false). +/// +/// \param[in] left left operand +/// \param[in] right right operand +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result KleeneAnd(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Element-wise OR of two boolean datums which always propagates nulls +/// (null and true is null). +/// +/// \param[in] left left operand +/// \param[in] right right operand +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Or(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR); + +/// \brief Element-wise OR of two boolean datums with a Kleene truth table +/// (null or true is true). +/// +/// \param[in] left left operand +/// \param[in] right right operand +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result KleeneOr(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR); + +/// \brief Element-wise XOR of two boolean datums +/// \param[in] left left operand +/// \param[in] right right operand +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Xor(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR); + +/// \brief Element-wise AND NOT of two boolean datums which always propagates nulls +/// (null and not true is null). +/// +/// \param[in] left left operand +/// \param[in] right right operand +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 3.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result AndNot(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR); + +/// \brief Element-wise AND NOT of two boolean datums with a Kleene truth table +/// (false and not null is false, null and not true is false). +/// +/// \param[in] left left operand +/// \param[in] right right operand +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 3.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result KleeneAndNot(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief IsIn returns true for each element of `values` that is contained in +/// `value_set` +/// +/// Behaviour of nulls is governed by SetLookupOptions::skip_nulls. +/// +/// \param[in] values array-like input to look up in value_set +/// \param[in] options SetLookupOptions +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result IsIn(const Datum& values, const SetLookupOptions& options, + ExecContext* ctx = NULLPTR); +ARROW_EXPORT +Result IsIn(const Datum& values, const Datum& value_set, + ExecContext* ctx = NULLPTR); + +/// \brief IndexIn examines each slot in the values against a value_set array. +/// If the value is not found in value_set, null will be output. +/// If found, the index of occurrence within value_set (ignoring duplicates) +/// will be output. +/// +/// For example given values = [99, 42, 3, null] and +/// value_set = [3, 3, 99], the output will be = [2, null, 0, null] +/// +/// Behaviour of nulls is governed by SetLookupOptions::skip_nulls. +/// +/// \param[in] values array-like input +/// \param[in] options SetLookupOptions +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result IndexIn(const Datum& values, const SetLookupOptions& options, + ExecContext* ctx = NULLPTR); +ARROW_EXPORT +Result IndexIn(const Datum& values, const Datum& value_set, + ExecContext* ctx = NULLPTR); + +/// \brief IsValid returns true for each element of `values` that is not null, +/// false otherwise +/// +/// \param[in] values input to examine for validity +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result IsValid(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief IsNull returns true for each element of `values` that is null, +/// false otherwise +/// +/// \param[in] values input to examine for nullity +/// \param[in] options NullOptions +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result IsNull(const Datum& values, NullOptions options = NullOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief IsNan returns true for each element of `values` that is NaN, +/// false otherwise +/// +/// \param[in] values input to look for NaN +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 3.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result IsNan(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief IfElse returns elements chosen from `left` or `right` +/// depending on `cond`. `null` values in `cond` will be promoted to the result +/// +/// \param[in] cond `Boolean` condition Scalar/ Array +/// \param[in] left Scalar/ Array +/// \param[in] right Scalar/ Array +/// \param[in] ctx the function execution context, optional +/// +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result IfElse(const Datum& cond, const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief CaseWhen behaves like a switch/case or if-else if-else statement: for +/// each row, select the first value for which the corresponding condition is +/// true, or (if given) select the 'else' value, else emit null. Note that a +/// null condition is the same as false. +/// +/// \param[in] cond Conditions (Boolean) +/// \param[in] cases Values (any type), along with an optional 'else' value. +/// \param[in] ctx the function execution context, optional +/// +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result CaseWhen(const Datum& cond, const std::vector& cases, + ExecContext* ctx = NULLPTR); + +/// \brief Year returns year for each element of `values` +/// +/// \param[in] values input to extract year from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Year(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief IsLeapYear returns if a year is a leap year for each element of `values` +/// +/// \param[in] values input to extract leap year indicator from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result IsLeapYear(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Month returns month for each element of `values`. +/// Month is encoded as January=1, December=12 +/// +/// \param[in] values input to extract month from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Month(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Day returns day number for each element of `values` +/// +/// \param[in] values input to extract day from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Day(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief YearMonthDay returns a struct containing the Year, Month and Day value for +/// each element of `values`. +/// +/// \param[in] values input to extract (year, month, day) struct from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 7.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result YearMonthDay(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief DayOfWeek returns number of the day of the week value for each element of +/// `values`. +/// +/// By default week starts on Monday denoted by 0 and ends on Sunday denoted +/// by 6. Start day of the week (Monday=1, Sunday=7) and numbering base (0 or 1) can be +/// set using DayOfWeekOptions +/// +/// \param[in] values input to extract number of the day of the week from +/// \param[in] options for setting start of the week and day numbering +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result DayOfWeek(const Datum& values, + DayOfWeekOptions options = DayOfWeekOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief DayOfYear returns number of day of the year for each element of `values`. +/// January 1st maps to day number 1, February 1st to 32, etc. +/// +/// \param[in] values input to extract number of day of the year from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result DayOfYear(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief ISOYear returns ISO year number for each element of `values`. +/// First week of an ISO year has the majority (4 or more) of its days in January. +/// +/// \param[in] values input to extract ISO year from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result ISOYear(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief USYear returns US epidemiological year number for each element of `values`. +/// First week of US epidemiological year has the majority (4 or more) of it's +/// days in January. Last week of US epidemiological year has the year's last +/// Wednesday in it. US epidemiological week starts on Sunday. +/// +/// \param[in] values input to extract US epidemiological year from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result USYear(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief ISOWeek returns ISO week of year number for each element of `values`. +/// First ISO week has the majority (4 or more) of its days in January. +/// ISO week starts on Monday. Year can have 52 or 53 weeks. +/// Week numbering can start with 1. +/// +/// \param[in] values input to extract ISO week of year from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result ISOWeek(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief USWeek returns US week of year number for each element of `values`. +/// First US week has the majority (4 or more) of its days in January. +/// US week starts on Sunday. Year can have 52 or 53 weeks. +/// Week numbering starts with 1. +/// +/// \param[in] values input to extract US week of year from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 6.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result USWeek(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Week returns week of year number for each element of `values`. +/// First ISO week has the majority (4 or more) of its days in January. +/// Year can have 52 or 53 weeks. Week numbering can start with 0 or 1 +/// depending on DayOfWeekOptions.count_from_zero. +/// +/// \param[in] values input to extract week of year from +/// \param[in] options for setting numbering start +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 6.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result Week(const Datum& values, WeekOptions options = WeekOptions(), + ExecContext* ctx = NULLPTR); + +/// \brief ISOCalendar returns a (ISO year, ISO week, ISO day of week) struct for +/// each element of `values`. +/// ISO week starts on Monday denoted by 1 and ends on Sunday denoted by 7. +/// +/// \param[in] values input to ISO calendar struct from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result ISOCalendar(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Quarter returns the quarter of year number for each element of `values` +/// First quarter maps to 1 and fourth quarter maps to 4. +/// +/// \param[in] values input to extract quarter of year from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result Quarter(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Hour returns hour value for each element of `values` +/// +/// \param[in] values input to extract hour from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Hour(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Minute returns minutes value for each element of `values` +/// +/// \param[in] values input to extract minutes from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Minute(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Second returns seconds value for each element of `values` +/// +/// \param[in] values input to extract seconds from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Second(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Millisecond returns number of milliseconds since the last full second +/// for each element of `values` +/// +/// \param[in] values input to extract milliseconds from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Millisecond(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Microsecond returns number of microseconds since the last full millisecond +/// for each element of `values` +/// +/// \param[in] values input to extract microseconds from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Microsecond(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Nanosecond returns number of nanoseconds since the last full millisecond +/// for each element of `values` +/// +/// \param[in] values input to extract nanoseconds from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Nanosecond(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Subsecond returns the fraction of second elapsed since last full second +/// as a float for each element of `values` +/// +/// \param[in] values input to extract subsecond from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result Subsecond(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Format timestamps according to a format string +/// +/// Return formatted time strings according to the format string +/// `StrftimeOptions::format` and to the locale specifier `Strftime::locale`. +/// +/// \param[in] values input timestamps +/// \param[in] options for setting format string and locale +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 6.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result Strftime(const Datum& values, StrftimeOptions options, + ExecContext* ctx = NULLPTR); + +/// \brief Parse timestamps according to a format string +/// +/// Return parsed timestamps according to the format string +/// `StrptimeOptions::format` at time resolution `Strftime::unit`. Parse errors are +/// raised depending on the `Strftime::error_is_null` setting. +/// +/// \param[in] values input strings +/// \param[in] options for setting format string, unit and error_is_null +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result Strptime(const Datum& values, StrptimeOptions options, + ExecContext* ctx = NULLPTR); + +/// \brief Converts timestamps from local timestamp without a timezone to a timestamp with +/// timezone, interpreting the local timestamp as being in the specified timezone for each +/// element of `values` +/// +/// \param[in] values input to convert +/// \param[in] options for setting source timezone, exception and ambiguous timestamp +/// handling. +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 6.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result AssumeTimezone(const Datum& values, + AssumeTimezoneOptions options, + ExecContext* ctx = NULLPTR); + +/// \brief IsDaylightSavings extracts if currently observing daylight savings for each +/// element of `values` +/// +/// \param[in] values input to extract daylight savings indicator from +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result IsDaylightSavings(const Datum& values, + ExecContext* ctx = NULLPTR); + +/// \brief LocalTimestamp converts timestamp to timezone naive local timestamp +/// +/// \param[in] values input to convert to local time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 12.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result LocalTimestamp(const Datum& values, + ExecContext* ctx = NULLPTR); + +/// \brief Years Between finds the number of years between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result YearsBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Quarters Between finds the number of quarters between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result QuartersBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Months Between finds the number of month between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result MonthsBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Weeks Between finds the number of weeks between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result WeeksBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Month Day Nano Between finds the number of months, days, and nanoseconds +/// between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result MonthDayNanoBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief DayTime Between finds the number of days and milliseconds between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result DayTimeBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Days Between finds the number of days between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result DaysBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Hours Between finds the number of hours between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result HoursBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Minutes Between finds the number of minutes between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result MinutesBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Seconds Between finds the number of hours between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result SecondsBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Milliseconds Between finds the number of milliseconds between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result MillisecondsBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Microseconds Between finds the number of microseconds between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result MicrosecondsBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Nanoseconds Between finds the number of nanoseconds between two values +/// +/// \param[in] left input treated as the start time +/// \param[in] right input treated as the end time +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result NanosecondsBetween(const Datum& left, const Datum& right, + ExecContext* ctx = NULLPTR); + +/// \brief Finds either the FIRST, LAST, or ALL items with a key that matches the given +/// query key in a map. +/// +/// Returns an array of items for FIRST and LAST, and an array of list of items for ALL. +/// +/// \param[in] map to look in +/// \param[in] options to pass a query key and choose which matching keys to return +/// (FIRST, LAST or ALL) +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 8.0.0 +/// \note API not yet finalized +ARROW_EXPORT Result MapLookup(const Datum& map, MapLookupOptions options, + ExecContext* ctx = NULLPTR); +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_vector.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_vector.h new file mode 100644 index 0000000000000000000000000000000000000000..159a787641ee5216ac2f19ec304d3d8e25303e39 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/api_vector.h @@ -0,0 +1,835 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/compute/function_options.h" +#include "arrow/compute/ordering.h" +#include "arrow/result.h" +#include "arrow/type_fwd.h" + +namespace arrow { +namespace compute { + +class ExecContext; + +/// \addtogroup compute-concrete-options +/// @{ + +class ARROW_EXPORT FilterOptions : public FunctionOptions { + public: + /// Configure the action taken when a slot of the selection mask is null + enum NullSelectionBehavior { + /// The corresponding filtered value will be removed in the output. + DROP, + /// The corresponding filtered value will be null in the output. + EMIT_NULL, + }; + + explicit FilterOptions(NullSelectionBehavior null_selection = DROP); + static constexpr const char kTypeName[] = "FilterOptions"; + static FilterOptions Defaults() { return FilterOptions(); } + + NullSelectionBehavior null_selection_behavior = DROP; +}; + +class ARROW_EXPORT TakeOptions : public FunctionOptions { + public: + explicit TakeOptions(bool boundscheck = true); + static constexpr const char kTypeName[] = "TakeOptions"; + static TakeOptions BoundsCheck() { return TakeOptions(true); } + static TakeOptions NoBoundsCheck() { return TakeOptions(false); } + static TakeOptions Defaults() { return BoundsCheck(); } + + bool boundscheck = true; +}; + +/// \brief Options for the dictionary encode function +class ARROW_EXPORT DictionaryEncodeOptions : public FunctionOptions { + public: + /// Configure how null values will be encoded + enum NullEncodingBehavior { + /// The null value will be added to the dictionary with a proper index. + ENCODE, + /// The null value will be masked in the indices array. + MASK + }; + + explicit DictionaryEncodeOptions(NullEncodingBehavior null_encoding = MASK); + static constexpr const char kTypeName[] = "DictionaryEncodeOptions"; + static DictionaryEncodeOptions Defaults() { return DictionaryEncodeOptions(); } + + NullEncodingBehavior null_encoding_behavior = MASK; +}; + +/// \brief Options for the run-end encode function +class ARROW_EXPORT RunEndEncodeOptions : public FunctionOptions { + public: + explicit RunEndEncodeOptions(std::shared_ptr run_end_type = int32()); + static constexpr const char kTypeName[] = "RunEndEncodeOptions"; + static RunEndEncodeOptions Defaults() { return RunEndEncodeOptions(); } + + std::shared_ptr run_end_type; +}; + +class ARROW_EXPORT ArraySortOptions : public FunctionOptions { + public: + explicit ArraySortOptions(SortOrder order = SortOrder::Ascending, + NullPlacement null_placement = NullPlacement::AtEnd); + static constexpr const char kTypeName[] = "ArraySortOptions"; + static ArraySortOptions Defaults() { return ArraySortOptions(); } + + /// Sorting order + SortOrder order; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; +}; + +class ARROW_EXPORT SortOptions : public FunctionOptions { + public: + explicit SortOptions(std::vector sort_keys = {}, + NullPlacement null_placement = NullPlacement::AtEnd); + explicit SortOptions(const Ordering& ordering); + static constexpr const char kTypeName[] = "SortOptions"; + static SortOptions Defaults() { return SortOptions(); } + /// Convenience constructor to create an ordering from SortOptions + /// + /// Note: Both classes contain the exact same information. However, + /// sort_options should only be used in a "function options" context while Ordering + /// is used more generally. + Ordering AsOrdering() && { return Ordering(std::move(sort_keys), null_placement); } + Ordering AsOrdering() const& { return Ordering(sort_keys, null_placement); } + + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; +}; + +/// \brief SelectK options +class ARROW_EXPORT SelectKOptions : public FunctionOptions { + public: + explicit SelectKOptions(int64_t k = -1, std::vector sort_keys = {}); + static constexpr const char kTypeName[] = "SelectKOptions"; + static SelectKOptions Defaults() { return SelectKOptions(); } + + static SelectKOptions TopKDefault(int64_t k, std::vector key_names = {}) { + std::vector keys; + for (const auto& name : key_names) { + keys.emplace_back(SortKey(name, SortOrder::Descending)); + } + if (key_names.empty()) { + keys.emplace_back(SortKey("not-used", SortOrder::Descending)); + } + return SelectKOptions{k, keys}; + } + static SelectKOptions BottomKDefault(int64_t k, + std::vector key_names = {}) { + std::vector keys; + for (const auto& name : key_names) { + keys.emplace_back(SortKey(name, SortOrder::Ascending)); + } + if (key_names.empty()) { + keys.emplace_back(SortKey("not-used", SortOrder::Ascending)); + } + return SelectKOptions{k, keys}; + } + + /// The number of `k` elements to keep. + int64_t k; + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; +}; + +/// \brief Rank options +class ARROW_EXPORT RankOptions : public FunctionOptions { + public: + /// Configure how ties between equal values are handled + enum Tiebreaker { + /// Ties get the smallest possible rank in sorted order. + Min, + /// Ties get the largest possible rank in sorted order. + Max, + /// Ranks are assigned in order of when ties appear in the input. + /// This ensures the ranks are a stable permutation of the input. + First, + /// The ranks span a dense [1, M] interval where M is the number + /// of distinct values in the input. + Dense + }; + + explicit RankOptions(std::vector sort_keys = {}, + NullPlacement null_placement = NullPlacement::AtEnd, + Tiebreaker tiebreaker = RankOptions::First); + /// Convenience constructor for array inputs + explicit RankOptions(SortOrder order, + NullPlacement null_placement = NullPlacement::AtEnd, + Tiebreaker tiebreaker = RankOptions::First) + : RankOptions({SortKey("", order)}, null_placement, tiebreaker) {} + + static constexpr const char kTypeName[] = "RankOptions"; + static RankOptions Defaults() { return RankOptions(); } + + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; + /// Tiebreaker for dealing with equal values in ranks + Tiebreaker tiebreaker; +}; + +/// \brief Quantile rank options +class ARROW_EXPORT RankQuantileOptions : public FunctionOptions { + public: + explicit RankQuantileOptions(std::vector sort_keys = {}, + NullPlacement null_placement = NullPlacement::AtEnd); + /// Convenience constructor for array inputs + explicit RankQuantileOptions(SortOrder order, + NullPlacement null_placement = NullPlacement::AtEnd) + : RankQuantileOptions({SortKey("", order)}, null_placement) {} + + static constexpr const char kTypeName[] = "RankQuantileOptions"; + static RankQuantileOptions Defaults() { return RankQuantileOptions(); } + + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement; +}; + +/// \brief Partitioning options for NthToIndices +class ARROW_EXPORT PartitionNthOptions : public FunctionOptions { + public: + explicit PartitionNthOptions(int64_t pivot, + NullPlacement null_placement = NullPlacement::AtEnd); + PartitionNthOptions() : PartitionNthOptions(0) {} + static constexpr const char kTypeName[] = "PartitionNthOptions"; + + /// The index into the equivalent sorted array of the partition pivot element. + int64_t pivot; + /// Whether nulls and NaNs are partitioned at the start or at the end + NullPlacement null_placement; +}; + +class ARROW_EXPORT WinsorizeOptions : public FunctionOptions { + public: + WinsorizeOptions(double lower_limit, double upper_limit); + WinsorizeOptions() : WinsorizeOptions(0, 1) {} + static constexpr const char kTypeName[] = "WinsorizeOptions"; + + /// The quantile below which all values are replaced with the quantile's value. + /// + /// For example, if lower_limit = 0.05, then all values in the lower 5% percentile + /// will be replaced with the 5% percentile value. + double lower_limit; + + /// The quantile above which all values are replaced with the quantile's value. + /// + /// For example, if upper_limit = 0.95, then all values in the upper 95% percentile + /// will be replaced with the 95% percentile value. + double upper_limit; +}; + +/// \brief Options for cumulative functions +/// \note Also aliased as CumulativeSumOptions for backward compatibility +class ARROW_EXPORT CumulativeOptions : public FunctionOptions { + public: + explicit CumulativeOptions(bool skip_nulls = false); + explicit CumulativeOptions(double start, bool skip_nulls = false); + explicit CumulativeOptions(std::shared_ptr start, bool skip_nulls = false); + static constexpr const char kTypeName[] = "CumulativeOptions"; + static CumulativeOptions Defaults() { return CumulativeOptions(); } + + /// Optional starting value for cumulative operation computation, default depends on the + /// operation and input type. + /// - sum: 0 + /// - prod: 1 + /// - min: maximum of the input type + /// - max: minimum of the input type + /// - mean: start is ignored because it has no meaning for mean + std::optional> start; + + /// If true, nulls in the input are ignored and produce a corresponding null output. + /// When false, the first null encountered is propagated through the remaining output. + bool skip_nulls = false; +}; +using CumulativeSumOptions = CumulativeOptions; // For backward compatibility + +/// \brief Options for pairwise functions +class ARROW_EXPORT PairwiseOptions : public FunctionOptions { + public: + explicit PairwiseOptions(int64_t periods = 1); + static constexpr const char kTypeName[] = "PairwiseOptions"; + static PairwiseOptions Defaults() { return PairwiseOptions(); } + + /// Periods to shift for applying the binary operation, accepts negative values. + int64_t periods = 1; +}; + +/// \brief Options for list_flatten function +class ARROW_EXPORT ListFlattenOptions : public FunctionOptions { + public: + explicit ListFlattenOptions(bool recursive = false); + static constexpr const char kTypeName[] = "ListFlattenOptions"; + static ListFlattenOptions Defaults() { return ListFlattenOptions(); } + + /// \brief If true, the list is flattened recursively until a non-list + /// array is formed. + bool recursive = false; +}; + +/// \brief Options for inverse_permutation function +class ARROW_EXPORT InversePermutationOptions : public FunctionOptions { + public: + explicit InversePermutationOptions( + int64_t max_index = -1, + std::optional> output_type = std::nullopt); + static constexpr const char kTypeName[] = "InversePermutationOptions"; + static InversePermutationOptions Defaults() { return InversePermutationOptions(); } + + /// \brief The max value in the input indices to allow. The length of the function's + /// output will be this value plus 1. If negative, this value will be set to the length + /// of the input indices minus 1 and the length of the function's output will be the + /// length of the input indices. + int64_t max_index = -1; + /// \brief The data type for the output array of inverse permutation. Defaults to the + /// type of the input indices when `nullopt`. Must be a signed integer type. An + /// invalid error will be reported if this type is not able to store the length of the + /// input indices. + std::optional> output_type; +}; + +/// \brief Options for scatter function +class ARROW_EXPORT ScatterOptions : public FunctionOptions { + public: + explicit ScatterOptions(int64_t max_index = -1); + static constexpr const char kTypeName[] = "ScatterOptions"; + static ScatterOptions Defaults() { return ScatterOptions(); } + + /// \brief The max value in the input indices to allow. The length of the function's + /// output will be this value plus 1. If negative, this value will be set to the length + /// of the input indices minus 1 and the length of the function's output will be the + /// length of the input indices. + int64_t max_index = -1; +}; + +/// @} + +/// \brief Filter with a boolean selection filter +/// +/// The output will be populated with values from the input at positions +/// where the selection filter is not 0. Nulls in the filter will be handled +/// based on options.null_selection_behavior. +/// +/// For example given values = ["a", "b", "c", null, "e", "f"] and +/// filter = [0, 1, 1, 0, null, 1], the output will be +/// (null_selection_behavior == DROP) = ["b", "c", "f"] +/// (null_selection_behavior == EMIT_NULL) = ["b", "c", null, "f"] +/// +/// \param[in] values array to filter +/// \param[in] filter indicates which values should be filtered out +/// \param[in] options configures null_selection_behavior +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result Filter(const Datum& values, const Datum& filter, + const FilterOptions& options = FilterOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +namespace internal { + +// These internal functions are implemented in kernels/vector_selection.cc + +/// \brief Return the number of selected indices in the boolean filter +/// +/// \param filter a plain or run-end encoded boolean array with or without nulls +/// \param null_selection how to handle nulls in the filter +ARROW_EXPORT +int64_t GetFilterOutputSize(const ArraySpan& filter, + FilterOptions::NullSelectionBehavior null_selection); + +/// \brief Compute uint64 selection indices for use with Take given a boolean +/// filter +/// +/// \param filter a plain or run-end encoded boolean array with or without nulls +/// \param null_selection how to handle nulls in the filter +ARROW_EXPORT +Result> GetTakeIndices( + const ArraySpan& filter, FilterOptions::NullSelectionBehavior null_selection, + MemoryPool* memory_pool = default_memory_pool()); + +} // namespace internal + +/// \brief ReplaceWithMask replaces each value in the array corresponding +/// to a true value in the mask with the next element from `replacements`. +/// +/// \param[in] values Array input to replace +/// \param[in] mask Array or Scalar of Boolean mask values +/// \param[in] replacements The replacement values to draw from. There must +/// be as many replacement values as true values in the mask. +/// \param[in] ctx the function execution context, optional +/// +/// \return the resulting datum +/// +/// \since 5.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result ReplaceWithMask(const Datum& values, const Datum& mask, + const Datum& replacements, ExecContext* ctx = NULLPTR); + +/// \brief FillNullForward fill null values in forward direction +/// +/// The output array will be of the same type as the input values +/// array, with replaced null values in forward direction. +/// +/// For example given values = ["a", "b", "c", null, null, "f"], +/// the output will be = ["a", "b", "c", "c", "c", "f"] +/// +/// \param[in] values datum from which to take +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result FillNullForward(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief FillNullBackward fill null values in backward direction +/// +/// The output array will be of the same type as the input values +/// array, with replaced null values in backward direction. +/// +/// For example given values = ["a", "b", "c", null, null, "f"], +/// the output will be = ["a", "b", "c", "f", "f", "f"] +/// +/// \param[in] values datum from which to take +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result FillNullBackward(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief Take from an array of values at indices in another array +/// +/// The output array will be of the same type as the input values +/// array, with elements taken from the values array at the given +/// indices. If an index is null then the taken element will be null. +/// +/// For example given values = ["a", "b", "c", null, "e", "f"] and +/// indices = [2, 1, null, 3], the output will be +/// = [values[2], values[1], null, values[3]] +/// = ["c", "b", null, null] +/// +/// \param[in] values datum from which to take +/// \param[in] indices which values to take +/// \param[in] options options +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result Take(const Datum& values, const Datum& indices, + const TakeOptions& options = TakeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Take with Array inputs and output +ARROW_EXPORT +Result> Take(const Array& values, const Array& indices, + const TakeOptions& options = TakeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Drop Null from an array of values +/// +/// The output array will be of the same type as the input values +/// array, with elements taken from the values array without nulls. +/// +/// For example given values = ["a", "b", "c", null, "e", "f"], +/// the output will be = ["a", "b", "c", "e", "f"] +/// +/// \param[in] values datum from which to take +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +ARROW_EXPORT +Result DropNull(const Datum& values, ExecContext* ctx = NULLPTR); + +/// \brief DropNull with Array inputs and output +ARROW_EXPORT +Result> DropNull(const Array& values, ExecContext* ctx = NULLPTR); + +/// \brief Return indices that partition an array around n-th sorted element. +/// +/// Find index of n-th(0 based) smallest value and perform indirect +/// partition of an array around that element. Output indices[0 ~ n-1] +/// holds values no greater than n-th element, and indices[n+1 ~ end] +/// holds values no less than n-th element. Elements in each partition +/// is not sorted. Nulls will be partitioned to the end of the output. +/// Output is not guaranteed to be stable. +/// +/// \param[in] values array to be partitioned +/// \param[in] n pivot array around sorted n-th element +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would partition an array +ARROW_EXPORT +Result> NthToIndices(const Array& values, int64_t n, + ExecContext* ctx = NULLPTR); + +/// \brief Return indices that partition an array around n-th sorted element. +/// +/// This overload takes a PartitionNthOptions specifying the pivot index +/// and the null handling. +/// +/// \param[in] values array to be partitioned +/// \param[in] options options including pivot index and null handling +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would partition an array +ARROW_EXPORT +Result> NthToIndices(const Array& values, + const PartitionNthOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return indices that would select the first `k` elements. +/// +/// Perform an indirect sort of the datum, keeping only the first `k` elements. The output +/// array will contain indices such that the item indicated by the k-th index will be in +/// the position it would be if the datum were sorted by `options.sort_keys`. However, +/// indices of null values will not be part of the output. The sort is not guaranteed to +/// be stable. +/// +/// \param[in] datum datum to be partitioned +/// \param[in] options options +/// \param[in] ctx the function execution context, optional +/// \return a datum with the same schema as the input +ARROW_EXPORT +Result> SelectKUnstable(const Datum& datum, + const SelectKOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort an array. +/// +/// Perform an indirect sort of array. The output array will contain +/// indices that would sort an array, which would be the same length +/// as input. Nulls will be stably partitioned to the end of the output +/// regardless of order. +/// +/// For example given array = [null, 1, 3.3, null, 2, 5.3] and order +/// = SortOrder::DESCENDING, the output will be [5, 2, 4, 1, 0, +/// 3]. +/// +/// \param[in] array array to sort +/// \param[in] order ascending or descending +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const Array& array, + SortOrder order = SortOrder::Ascending, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort an array. +/// +/// This overload takes a ArraySortOptions specifying the sort order +/// and the null handling. +/// +/// \param[in] array array to sort +/// \param[in] options options including sort order and null handling +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const Array& array, + const ArraySortOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort a chunked array. +/// +/// Perform an indirect sort of chunked array. The output array will +/// contain indices that would sort a chunked array, which would be +/// the same length as input. Nulls will be stably partitioned to the +/// end of the output regardless of order. +/// +/// For example given chunked_array = [[null, 1], [3.3], [null, 2, +/// 5.3]] and order = SortOrder::DESCENDING, the output will be [5, 2, +/// 4, 1, 0, 3]. +/// +/// \param[in] chunked_array chunked array to sort +/// \param[in] order ascending or descending +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const ChunkedArray& chunked_array, + SortOrder order = SortOrder::Ascending, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort a chunked array. +/// +/// This overload takes a ArraySortOptions specifying the sort order +/// and the null handling. +/// +/// \param[in] chunked_array chunked array to sort +/// \param[in] options options including sort order and null handling +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort an array +ARROW_EXPORT +Result> SortIndices(const ChunkedArray& chunked_array, + const ArraySortOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Return the indices that would sort an input in the +/// specified order. Input is one of array, chunked array record batch +/// or table. +/// +/// Perform an indirect sort of input. The output array will contain +/// indices that would sort an input, which would be the same length +/// as input. Nulls will be stably partitioned to the start or to the end +/// of the output depending on SortOrder::null_placement. +/// +/// For example given input (table) = { +/// "column1": [[null, 1], [ 3, null, 2, 1]], +/// "column2": [[ 5], [3, null, null, 5, 5]], +/// } and options = { +/// {"column1", SortOrder::Ascending}, +/// {"column2", SortOrder::Descending}, +/// }, the output will be [5, 1, 4, 2, 0, 3]. +/// +/// \param[in] datum array, chunked array, record batch or table to sort +/// \param[in] options options +/// \param[in] ctx the function execution context, optional +/// \return offsets indices that would sort a table +ARROW_EXPORT +Result> SortIndices(const Datum& datum, const SortOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Compute unique elements from an array-like object +/// +/// Note if a null occurs in the input it will NOT be included in the output. +/// +/// \param[in] datum array-like input +/// \param[in] ctx the function execution context, optional +/// \return result as Array +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result> Unique(const Datum& datum, ExecContext* ctx = NULLPTR); + +// Constants for accessing the output of ValueCounts +ARROW_EXPORT extern const char kValuesFieldName[]; +ARROW_EXPORT extern const char kCountsFieldName[]; +ARROW_EXPORT extern const int32_t kValuesFieldIndex; +ARROW_EXPORT extern const int32_t kCountsFieldIndex; + +/// \brief Return counts of unique elements from an array-like object. +/// +/// Note that the counts do not include counts for nulls in the array. These can be +/// obtained separately from metadata. +/// +/// For floating point arrays there is no attempt to normalize -0.0, 0.0 and NaN values +/// which can lead to unexpected results if the input Array has these values. +/// +/// \param[in] value array-like input +/// \param[in] ctx the function execution context, optional +/// \return counts An array of structs. +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result> ValueCounts(const Datum& value, + ExecContext* ctx = NULLPTR); + +/// \brief Dictionary-encode values in an array-like object +/// +/// Any nulls encountered in the dictionary will be handled according to the +/// specified null encoding behavior. +/// +/// For example, given values ["a", "b", null, "a", null] the output will be +/// (null_encoding == ENCODE) Indices: [0, 1, 2, 0, 2] / Dict: ["a", "b", null] +/// (null_encoding == MASK) Indices: [0, 1, null, 0, null] / Dict: ["a", "b"] +/// +/// If the input is already dictionary encoded this function is a no-op unless +/// it needs to modify the null_encoding (TODO) +/// +/// \param[in] data array-like input +/// \param[in] ctx the function execution context, optional +/// \param[in] options configures null encoding behavior +/// \return result with same shape and type as input +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result DictionaryEncode( + const Datum& data, + const DictionaryEncodeOptions& options = DictionaryEncodeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Run-end-encode values in an array-like object +/// +/// The returned run-end encoded type uses the same value type of the input and +/// run-end type defined in the options. +/// +/// \param[in] value array-like input +/// \param[in] options configures encoding behavior +/// \param[in] ctx the function execution context, optional +/// \return result with same shape but run-end encoded +/// +/// \since 12.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result RunEndEncode( + const Datum& value, + const RunEndEncodeOptions& options = RunEndEncodeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Decode a Run-End Encoded array to a plain array +/// +/// The output data type is the same as the values array type of run-end encoded +/// input. +/// +/// \param[in] value run-end-encoded input +/// \param[in] ctx the function execution context, optional +/// \return plain array resulting from decoding the run-end encoded input +/// +/// \since 12.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result RunEndDecode(const Datum& value, ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative sum of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative sum behavior +/// \param[in] check_overflow whether to check for overflow, if true, return Invalid +/// status on overflow, otherwise wrap around on overflow +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeSum( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + bool check_overflow = false, ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative product of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative prod behavior +/// \param[in] check_overflow whether to check for overflow, if true, return Invalid +/// status on overflow, otherwise wrap around on overflow +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeProd( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + bool check_overflow = false, ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative max of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative max behavior +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeMax( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative min of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative min behavior +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeMin( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Compute the cumulative mean of an array-like object +/// +/// \param[in] values array-like input +/// \param[in] options configures cumulative mean behavior, `start` is ignored +/// \param[in] ctx the function execution context, optional +ARROW_EXPORT +Result CumulativeMean( + const Datum& values, const CumulativeOptions& options = CumulativeOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Return the first order difference of an array. +/// +/// Computes the first order difference of an array, i.e. +/// output[i] = input[i] - input[i - p] if i >= p +/// output[i] = null otherwise +/// where p is the period. For example, with p = 1, +/// Diff([1, 4, 9, 10, 15]) = [null, 3, 5, 1, 5]. +/// With p = 2, +/// Diff([1, 4, 9, 10, 15]) = [null, null, 8, 6, 6] +/// p can also be negative, in which case the diff is computed in +/// the opposite direction. +/// \param[in] array array input +/// \param[in] options options, specifying overflow behavior and period +/// \param[in] check_overflow whether to return error on overflow +/// \param[in] ctx the function execution context, optional +/// \return result as array +ARROW_EXPORT +Result> PairwiseDiff(const Array& array, + const PairwiseOptions& options, + bool check_overflow = false, + ExecContext* ctx = NULLPTR); + +/// \brief Return the inverse permutation of the given indices. +/// +/// For indices[i] = x, inverse_permutation[x] = i. And inverse_permutation[x] = null if x +/// does not appear in the input indices. Indices must be in the range of [0, max_index], +/// or null, which will be ignored. If multiple indices point to the same value, the last +/// one is used. +/// +/// For example, with +/// indices = [null, 0, null, 2, 4, 1, 1] +/// the inverse permutation is +/// [1, 6, 3, null, 4, null, null] +/// if max_index = 6. +/// +/// \param[in] indices array-like indices +/// \param[in] options configures the max index and the output type +/// \param[in] ctx the function execution context, optional +/// \return the resulting inverse permutation +/// +/// \since 20.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result InversePermutation( + const Datum& indices, + const InversePermutationOptions& options = InversePermutationOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +/// \brief Scatter the values into specified positions according to the indices. +/// +/// For indices[i] = x, output[x] = values[i]. And output[x] = null if x does not appear +/// in the input indices. Indices must be in the range of [0, max_index], or null, in +/// which case the corresponding value will be ignored. If multiple indices point to the +/// same value, the last one is used. +/// +/// For example, with +/// values = [a, b, c, d, e, f, g] +/// indices = [null, 0, null, 2, 4, 1, 1] +/// the output is +/// [b, g, d, null, e, null, null] +/// if max_index = 6. +/// +/// \param[in] values datum to scatter +/// \param[in] indices array-like indices +/// \param[in] options configures the max index of to scatter +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 20.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Scatter(const Datum& values, const Datum& indices, + const ScatterOptions& options = ScatterOptions::Defaults(), + ExecContext* ctx = NULLPTR); + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/cast.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/cast.h new file mode 100644 index 0000000000000000000000000000000000000000..ec5818239acb1ab52b06945a5fb4e60f84b58b61 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/cast.h @@ -0,0 +1,134 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/compute/function.h" +#include "arrow/compute/function_options.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class Array; + +namespace compute { + +class ExecContext; + +/// \addtogroup compute-concrete-options +/// @{ + +class ARROW_EXPORT CastOptions : public FunctionOptions { + public: + explicit CastOptions(bool safe = true); + + static constexpr const char kTypeName[] = "CastOptions"; + static CastOptions Safe(TypeHolder to_type = {}) { + CastOptions safe(true); + safe.to_type = std::move(to_type); + return safe; + } + + static CastOptions Unsafe(TypeHolder to_type = {}) { + CastOptions unsafe(false); + unsafe.to_type = std::move(to_type); + return unsafe; + } + + // Type being casted to. May be passed separate to eager function + // compute::Cast + TypeHolder to_type; + + bool allow_int_overflow; + bool allow_time_truncate; + bool allow_time_overflow; + bool allow_decimal_truncate; + bool allow_float_truncate; + // Indicate if conversions from Binary/FixedSizeBinary to string must + // validate the utf8 payload. + bool allow_invalid_utf8; + + /// true if the safety options all match CastOptions::Safe + /// + /// Note, if this returns false it does not mean is_unsafe will return true + bool is_safe() const; + /// true if the safety options all match CastOptions::Unsafe + /// + /// Note, if this returns false it does not mean is_safe will return true + bool is_unsafe() const; +}; + +/// @} + +/// \brief Return true if a cast function is defined +ARROW_EXPORT +bool CanCast(const DataType& from_type, const DataType& to_type); + +// ---------------------------------------------------------------------- +// Convenience invocation APIs for a number of kernels + +/// \brief Cast from one array type to another +/// \param[in] value array to cast +/// \param[in] to_type type to cast to +/// \param[in] options casting options +/// \param[in] ctx the function execution context, optional +/// \return the resulting array +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result> Cast(const Array& value, const TypeHolder& to_type, + const CastOptions& options = CastOptions::Safe(), + ExecContext* ctx = NULLPTR); + +/// \brief Cast from one array type to another +/// \param[in] value array to cast +/// \param[in] options casting options. The "to_type" field must be populated +/// \param[in] ctx the function execution context, optional +/// \return the resulting array +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Cast(const Datum& value, const CastOptions& options, + ExecContext* ctx = NULLPTR); + +/// \brief Cast from one value to another +/// \param[in] value datum to cast +/// \param[in] to_type type to cast to +/// \param[in] options casting options +/// \param[in] ctx the function execution context, optional +/// \return the resulting datum +/// +/// \since 1.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result Cast(const Datum& value, const TypeHolder& to_type, + const CastOptions& options = CastOptions::Safe(), + ExecContext* ctx = NULLPTR); + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/exec.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/exec.h new file mode 100644 index 0000000000000000000000000000000000000000..dae7e1ea686829fcf9b11bf07489d2cca8610f2b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/exec.h @@ -0,0 +1,489 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/array/data.h" +#include "arrow/compute/expression.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/datum.h" +#include "arrow/result.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace compute { + +// It seems like 64K might be a good default chunksize to use for execution +// based on the experience of other query processing systems. The current +// default is not to chunk contiguous arrays, though, but this may change in +// the future once parallel execution is implemented +static constexpr int64_t kDefaultExecChunksize = UINT16_MAX; + +/// \brief Context for expression-global variables and options used by +/// function evaluation +class ARROW_EXPORT ExecContext { + public: + // If no function registry passed, the default is used. + explicit ExecContext(MemoryPool* pool = default_memory_pool(), + ::arrow::internal::Executor* executor = NULLPTR, + FunctionRegistry* func_registry = NULLPTR); + + /// \brief The MemoryPool used for allocations, default is + /// default_memory_pool(). + MemoryPool* memory_pool() const { return pool_; } + + const ::arrow::internal::CpuInfo* cpu_info() const; + + /// \brief An Executor which may be used to parallelize execution. + ::arrow::internal::Executor* executor() const { return executor_; } + + /// \brief The FunctionRegistry for looking up functions by name and + /// selecting kernels for execution. Defaults to the library-global function + /// registry provided by GetFunctionRegistry. + FunctionRegistry* func_registry() const { return func_registry_; } + + // \brief Set maximum length unit of work for kernel execution. Larger + // contiguous array inputs will be split into smaller chunks, and, if + // possible and enabled, processed in parallel. The default chunksize is + // INT64_MAX, so contiguous arrays are not split. + void set_exec_chunksize(int64_t chunksize) { exec_chunksize_ = chunksize; } + + // \brief Maximum length for ExecBatch data chunks processed by + // kernels. Contiguous array inputs with longer length will be split into + // smaller chunks. + int64_t exec_chunksize() const { return exec_chunksize_; } + + /// \brief Set whether to use multiple threads for function execution. This + /// is not yet used. + void set_use_threads(bool use_threads = true) { use_threads_ = use_threads; } + + /// \brief If true, then utilize multiple threads where relevant for function + /// execution. This is not yet used. + bool use_threads() const { return use_threads_; } + + // Set the preallocation strategy for kernel execution as it relates to + // chunked execution. For chunked execution, whether via ChunkedArray inputs + // or splitting larger Array arguments into smaller pieces, contiguous + // allocation (if permitted by the kernel) will allocate one large array to + // write output into yielding it to the caller at the end. If this option is + // set to off, then preallocations will be performed independently for each + // chunk of execution + // + // TODO: At some point we might want the limit the size of contiguous + // preallocations. For example, even if the exec_chunksize is 64K or less, we + // might limit contiguous allocations to 1M records, say. + void set_preallocate_contiguous(bool preallocate) { + preallocate_contiguous_ = preallocate; + } + + /// \brief If contiguous preallocations should be used when doing chunked + /// execution as specified by exec_chunksize(). See + /// set_preallocate_contiguous() for more information. + bool preallocate_contiguous() const { return preallocate_contiguous_; } + + private: + MemoryPool* pool_; + ::arrow::internal::Executor* executor_; + FunctionRegistry* func_registry_; + int64_t exec_chunksize_ = std::numeric_limits::max(); + bool preallocate_contiguous_ = true; + bool use_threads_ = true; +}; + +// TODO: Consider standardizing on uint16 selection vectors and only use them +// when we can ensure that each value is 64K length or smaller + +/// \brief Container for an array of value selection indices that were +/// materialized from a filter. +/// +/// Columnar query engines (see e.g. [1]) have found that rather than +/// materializing filtered data, the filter can instead be converted to an +/// array of the "on" indices and then "fusing" these indices in operator +/// implementations. This is especially relevant for aggregations but also +/// applies to scalar operations. +/// +/// We are not yet using this so this is mostly a placeholder for now. +/// +/// [1]: http://cidrdb.org/cidr2005/papers/P19.pdf +class ARROW_EXPORT SelectionVector { + public: + explicit SelectionVector(std::shared_ptr data); + + explicit SelectionVector(const Array& arr); + + /// \brief Create SelectionVector from boolean mask + static Result> FromMask(const BooleanArray& arr); + + const int32_t* indices() const { return indices_; } + int32_t length() const; + + private: + std::shared_ptr data_; + const int32_t* indices_; +}; + +/// An index to represent that a batch does not belong to an ordered stream +constexpr int64_t kUnsequencedIndex = -1; + +/// \brief A unit of work for kernel execution. It contains a collection of +/// Array and Scalar values and an optional SelectionVector indicating that +/// there is an unmaterialized filter that either must be materialized, or (if +/// the kernel supports it) pushed down into the kernel implementation. +/// +/// ExecBatch is semantically similar to RecordBatch in that in a SQL context +/// it represents a collection of records, but constant "columns" are +/// represented by Scalar values rather than having to be converted into arrays +/// with repeated values. +/// +/// TODO: Datum uses arrow/util/variant.h which may be a bit heavier-weight +/// than is desirable for this class. Microbenchmarks would help determine for +/// sure. See ARROW-8928. + +/// \addtogroup acero-internals +/// @{ + +struct ARROW_EXPORT ExecBatch { + ExecBatch() = default; + ExecBatch(std::vector values, int64_t length) + : values(std::move(values)), length(length) {} + + explicit ExecBatch(const RecordBatch& batch); + + /// \brief Infer the ExecBatch length from values. + static Result InferLength(const std::vector& values); + + /// Creates an ExecBatch with length-validation. + /// + /// If any value is given, then all values must have a common length. If the given + /// length is negative, then the length of the ExecBatch is set to this common length, + /// or to 1 if no values are given. Otherwise, the given length must equal the common + /// length, if any value is given. + static Result Make(std::vector values, int64_t length = -1); + + Result> ToRecordBatch( + std::shared_ptr schema, MemoryPool* pool = default_memory_pool()) const; + + /// The values representing positional arguments to be passed to a kernel's + /// exec function for processing. + std::vector values; + + /// A deferred filter represented as an array of indices into the values. + /// + /// For example, the filter [true, true, false, true] would be represented as + /// the selection vector [0, 1, 3]. When the selection vector is set, + /// ExecBatch::length is equal to the length of this array. + std::shared_ptr selection_vector; + + /// A predicate Expression guaranteed to evaluate to true for all rows in this batch. + Expression guarantee = literal(true); + + /// The semantic length of the ExecBatch. When the values are all scalars, + /// the length should be set to 1 for non-aggregate kernels, otherwise the + /// length is taken from the array values, except when there is a selection + /// vector. When there is a selection vector set, the length of the batch is + /// the length of the selection. Aggregate kernels can have an ExecBatch + /// formed by projecting just the partition columns from a batch in which + /// case, it would have scalar rows with length greater than 1. + /// + /// If the array values are of length 0 then the length is 0 regardless of + /// whether any values are Scalar. + int64_t length = 0; + + /// \brief index of this batch in a sorted stream of batches + /// + /// This index must be strictly monotonic starting at 0 without gaps or + /// it can be set to kUnsequencedIndex if there is no meaningful order + int64_t index = kUnsequencedIndex; + + /// \brief The sum of bytes in each buffer referenced by the batch + /// + /// Note: Scalars are not counted + /// Note: Some values may referenced only part of a buffer, for + /// example, an array with an offset. The actual data + /// visible to this batch will be smaller than the total + /// buffer size in this case. + int64_t TotalBufferSize() const; + + /// \brief Return the value at the i-th index + template + inline const Datum& operator[](index_type i) const { + return values[i]; + } + + bool Equals(const ExecBatch& other) const; + + /// \brief A convenience for the number of values / arguments. + int num_values() const { return static_cast(values.size()); } + + ExecBatch Slice(int64_t offset, int64_t length) const; + + Result SelectValues(const std::vector& ids) const; + + /// \brief A convenience for returning the types from the batch. + std::vector GetTypes() const { + std::vector result; + for (const auto& value : this->values) { + result.emplace_back(value.type()); + } + return result; + } + + std::string ToString() const; +}; + +inline bool operator==(const ExecBatch& l, const ExecBatch& r) { return l.Equals(r); } +inline bool operator!=(const ExecBatch& l, const ExecBatch& r) { return !l.Equals(r); } + +ARROW_EXPORT void PrintTo(const ExecBatch&, std::ostream*); + +/// @} + +/// \defgroup compute-internals Utilities for calling functions, useful for those +/// extending the function registry +/// +/// @{ + +struct ExecValue { + ArraySpan array = {}; + const Scalar* scalar = NULLPTR; + + ExecValue(const Scalar* scalar) // NOLINT implicit conversion + : scalar(scalar) {} + + ExecValue(ArraySpan array) // NOLINT implicit conversion + : array(std::move(array)) {} + + ExecValue(const ArrayData& array) { // NOLINT implicit conversion + this->array.SetMembers(array); + } + + ExecValue() = default; + ExecValue(const ExecValue& other) = default; + ExecValue& operator=(const ExecValue& other) = default; + ExecValue(ExecValue&& other) = default; + ExecValue& operator=(ExecValue&& other) = default; + + int64_t length() const { return this->is_array() ? this->array.length : 1; } + + bool is_array() const { return this->scalar == NULLPTR; } + bool is_scalar() const { return !this->is_array(); } + + void SetArray(const ArrayData& array) { + this->array.SetMembers(array); + this->scalar = NULLPTR; + } + + void SetScalar(const Scalar* scalar) { this->scalar = scalar; } + + template + const ExactType& scalar_as() const { + return ::arrow::internal::checked_cast(*this->scalar); + } + + /// XXX: here temporarily for compatibility with datum, see + /// e.g. MakeStructExec in scalar_nested.cc + int64_t null_count() const { + if (this->is_array()) { + return this->array.GetNullCount(); + } else { + return this->scalar->is_valid ? 0 : 1; + } + } + + const DataType* type() const { + if (this->is_array()) { + return array.type; + } else { + return scalar->type.get(); + } + } +}; + +struct ARROW_EXPORT ExecResult { + // The default value of the variant is ArraySpan + std::variant> value; + + int64_t length() const { + if (this->is_array_span()) { + return this->array_span()->length; + } else { + return this->array_data()->length; + } + } + + const DataType* type() const { + if (this->is_array_span()) { + return this->array_span()->type; + } else { + return this->array_data()->type.get(); + } + } + + const ArraySpan* array_span() const { return &std::get(this->value); } + ArraySpan* array_span_mutable() { return &std::get(this->value); } + + bool is_array_span() const { return this->value.index() == 0; } + + const std::shared_ptr& array_data() const { + return std::get>(this->value); + } + ArrayData* array_data_mutable() { + return std::get>(this->value).get(); + } + + bool is_array_data() const { return this->value.index() == 1; } +}; + +/// \brief A "lightweight" column batch object which contains no +/// std::shared_ptr objects and does not have any memory ownership +/// semantics. Can represent a view onto an "owning" ExecBatch. +struct ARROW_EXPORT ExecSpan { + ExecSpan() = default; + ExecSpan(const ExecSpan& other) = default; + ExecSpan& operator=(const ExecSpan& other) = default; + ExecSpan(ExecSpan&& other) = default; + ExecSpan& operator=(ExecSpan&& other) = default; + + explicit ExecSpan(std::vector values, int64_t length) + : length(length), values(std::move(values)) {} + + explicit ExecSpan(const ExecBatch& batch) { + this->length = batch.length; + this->values.resize(batch.values.size()); + for (size_t i = 0; i < batch.values.size(); ++i) { + const Datum& in_value = batch[i]; + ExecValue* out_value = &this->values[i]; + if (in_value.is_array()) { + out_value->SetArray(*in_value.array()); + } else { + out_value->SetScalar(in_value.scalar().get()); + } + } + } + + /// \brief Return the value at the i-th index + template + inline const ExecValue& operator[](index_type i) const { + return values[i]; + } + + /// \brief A convenience for the number of values / arguments. + int num_values() const { return static_cast(values.size()); } + + std::vector GetTypes() const { + std::vector result; + for (const auto& value : this->values) { + result.emplace_back(value.type()); + } + return result; + } + + ExecBatch ToExecBatch() const { + ExecBatch result; + result.length = this->length; + for (const ExecValue& value : this->values) { + if (value.is_array()) { + result.values.push_back(value.array.ToArrayData()); + } else { + result.values.push_back(value.scalar->GetSharedPtr()); + } + } + return result; + } + + int64_t length = 0; + std::vector values; +}; + +/// \defgroup compute-call-function One-shot calls to compute functions +/// +/// @{ + +/// \brief One-shot invoker for all types of functions. +/// +/// Does kernel dispatch, argument checking, iteration of ChunkedArray inputs, +/// and wrapping of outputs. +ARROW_EXPORT +Result CallFunction(const std::string& func_name, const std::vector& args, + const FunctionOptions* options, ExecContext* ctx = NULLPTR); + +/// \brief Variant of CallFunction which uses a function's default options. +/// +/// NB: Some functions require FunctionOptions be provided. +ARROW_EXPORT +Result CallFunction(const std::string& func_name, const std::vector& args, + ExecContext* ctx = NULLPTR); + +/// \brief One-shot invoker for all types of functions. +/// +/// Does kernel dispatch, argument checking, iteration of ChunkedArray inputs, +/// and wrapping of outputs. +ARROW_EXPORT +Result CallFunction(const std::string& func_name, const ExecBatch& batch, + const FunctionOptions* options, ExecContext* ctx = NULLPTR); + +/// \brief Variant of CallFunction which uses a function's default options. +/// +/// NB: Some functions require FunctionOptions be provided. +ARROW_EXPORT +Result CallFunction(const std::string& func_name, const ExecBatch& batch, + ExecContext* ctx = NULLPTR); + +/// @} + +/// \defgroup compute-function-executor One-shot calls to obtain function executors +/// +/// @{ + +/// \brief One-shot executor provider for all types of functions. +/// +/// This function creates and initializes a `FunctionExecutor` appropriate +/// for the given function name, input types and function options. +ARROW_EXPORT +Result> GetFunctionExecutor( + const std::string& func_name, std::vector in_types, + const FunctionOptions* options = NULLPTR, FunctionRegistry* func_registry = NULLPTR); + +/// \brief One-shot executor provider for all types of functions. +/// +/// This function creates and initializes a `FunctionExecutor` appropriate +/// for the given function name, input types (taken from the Datum arguments) +/// and function options. +ARROW_EXPORT +Result> GetFunctionExecutor( + const std::string& func_name, const std::vector& args, + const FunctionOptions* options = NULLPTR, FunctionRegistry* func_registry = NULLPTR); + +/// @} + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/expression.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/expression.h new file mode 100644 index 0000000000000000000000000000000000000000..b8ce50675c8c9bb0a3a7081a23c6bd3c2002f2d1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/expression.h @@ -0,0 +1,295 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/compute/type_fwd.h" +#include "arrow/datum.h" +#include "arrow/type_fwd.h" +#include "arrow/util/small_vector.h" + +namespace arrow { +namespace compute { + +/// \defgroup expression-core Expressions to describe data transformations +/// +/// @{ + +/// An unbound expression which maps a single Datum to another Datum. +/// An expression is one of +/// - A literal Datum. +/// - A reference to a single (potentially nested) field of the input Datum. +/// - A call to a compute function, with arguments specified by other Expressions. +class ARROW_EXPORT Expression { + public: + struct Call { + std::string function_name; + std::vector arguments; + std::shared_ptr options; + // Cached hash value + size_t hash; + + // post-Bind properties: + std::shared_ptr function; + const Kernel* kernel = NULLPTR; + std::shared_ptr kernel_state; + TypeHolder type; + + void ComputeHash(); + }; + + std::string ToString() const; + bool Equals(const Expression& other) const; + size_t hash() const; + struct Hash { + size_t operator()(const Expression& expr) const { return expr.hash(); } + }; + + /// Bind this expression to the given input type, looking up Kernels and field types. + /// Some expression simplification may be performed and implicit casts will be inserted. + /// Any state necessary for execution will be initialized and returned. + Result Bind(const TypeHolder& in, ExecContext* = NULLPTR) const; + Result Bind(const Schema& in_schema, ExecContext* = NULLPTR) const; + + // XXX someday + // Clone all KernelState in this bound expression. If any function referenced by this + // expression has mutable KernelState, it is not safe to execute or apply simplification + // passes to it (or copies of it!) from multiple threads. Cloning state produces new + // KernelStates where necessary to ensure that Expressions may be manipulated safely + // on multiple threads. + // Result CloneState() const; + // Status SetState(ExpressionState); + + /// Return true if all an expression's field references have explicit types + /// and all of its functions' kernels are looked up. + bool IsBound() const; + + /// Return true if this expression is composed only of Scalar literals, field + /// references, and calls to ScalarFunctions. + bool IsScalarExpression() const; + + /// Return true if this expression is literal and entirely null. + bool IsNullLiteral() const; + + /// Return true if this expression could evaluate to true. Will return true for any + /// unbound or non-boolean Expressions. IsSatisfiable does not (currently) do any + /// canonicalization or simplification of the expression, so even Expressions + /// which are unsatisfiable may spuriously return `true` here. This function is + /// intended for use in predicate pushdown where a filter expression is simplified + /// by a guarantee, so it assumes that trying to simplify again would be redundant. + bool IsSatisfiable() const; + + // XXX someday + // Result GetPipelines(); + + bool is_valid() const { return impl_ != NULLPTR; } + + /// Access a Call or return nullptr if this expression is not a call + const Call* call() const; + /// Access a Datum or return nullptr if this expression is not a literal + const Datum* literal() const; + /// Access a FieldRef or return nullptr if this expression is not a field_ref + const FieldRef* field_ref() const; + + /// The type to which this expression will evaluate + const DataType* type() const; + // XXX someday + // NullGeneralization::type nullable() const; + + struct Parameter { + FieldRef ref; + + // post-bind properties + TypeHolder type; + ::arrow::internal::SmallVector indices; + }; + const Parameter* parameter() const; + + Expression() = default; + explicit Expression(Call call); + explicit Expression(Datum literal); + explicit Expression(Parameter parameter); + + static bool Identical(const Expression& l, const Expression& r); + + private: + using Impl = std::variant; + std::shared_ptr impl_; +}; + +inline bool operator==(const Expression& l, const Expression& r) { return l.Equals(r); } +inline bool operator!=(const Expression& l, const Expression& r) { return !l.Equals(r); } + +ARROW_EXPORT void PrintTo(const Expression&, std::ostream*); + +// Factories + +ARROW_EXPORT +Expression literal(Datum lit); + +template +Expression literal(Arg&& arg) { + return literal(Datum(std::forward(arg))); +} + +ARROW_EXPORT +Expression field_ref(FieldRef ref); + +ARROW_EXPORT +Expression call(std::string function, std::vector arguments, + std::shared_ptr options = NULLPTR); + +template ::value>::type> +Expression call(std::string function, std::vector arguments, + Options options) { + return call(std::move(function), std::move(arguments), + std::make_shared(std::move(options))); +} + +/// Assemble a list of all fields referenced by an Expression at any depth. +ARROW_EXPORT +std::vector FieldsInExpression(const Expression&); + +/// Check if the expression references any fields. +ARROW_EXPORT +bool ExpressionHasFieldRefs(const Expression&); + +struct ARROW_EXPORT KnownFieldValues; + +/// Assemble a mapping from field references to known values. This derives known values +/// from "equal" and "is_null" Expressions referencing a field and a literal. +ARROW_EXPORT +Result ExtractKnownFieldValues( + const Expression& guaranteed_true_predicate); + +/// @} + +/// \defgroup expression-passes Functions for modification of Expressions +/// +/// @{ +/// +/// These transform bound expressions. Some transforms utilize a guarantee, which is +/// provided as an Expression which is guaranteed to evaluate to true. The +/// guaranteed_true_predicate need not be bound, but canonicalization is currently +/// deferred to producers of guarantees. For example in order to be recognized as a +/// guarantee on a field value, an Expression must be a call to "equal" with field_ref LHS +/// and literal RHS. Flipping the arguments, "is_in" with a one-long value_set, ... or +/// other semantically identical Expressions will not be recognized. + +/// Weak canonicalization which establishes guarantees for subsequent passes. Even +/// equivalent Expressions may result in different canonicalized expressions. +/// TODO this could be a strong canonicalization +ARROW_EXPORT +Result Canonicalize(Expression, ExecContext* = NULLPTR); + +/// Simplify Expressions based on literal arguments (for example, add(null, x) will always +/// be null so replace the call with a null literal). Includes early evaluation of all +/// calls whose arguments are entirely literal. +ARROW_EXPORT +Result FoldConstants(Expression); + +/// Simplify Expressions by replacing with known values of the fields which it references. +ARROW_EXPORT +Result ReplaceFieldsWithKnownValues(const KnownFieldValues& known_values, + Expression); + +/// Simplify an expression by replacing subexpressions based on a guarantee: +/// a boolean expression which is guaranteed to evaluate to `true`. For example, this is +/// used to remove redundant function calls from a filter expression or to replace a +/// reference to a constant-value field with a literal. +ARROW_EXPORT +Result SimplifyWithGuarantee(Expression, + const Expression& guaranteed_true_predicate); + +/// Replace all named field refs (e.g. "x" or "x.y") with field paths (e.g. [0] or [1,3]) +/// +/// This isn't usually needed and does not offer any simplification by itself. However, +/// it can be useful to normalize an expression to paths to make it simpler to work with. +ARROW_EXPORT Result RemoveNamedRefs(Expression expression); + +/// @} + +// Execution + +/// Create an ExecBatch suitable for passing to ExecuteScalarExpression() from a +/// RecordBatch which may have missing or incorrectly ordered columns. +/// Missing fields will be replaced with null scalars. +ARROW_EXPORT Result MakeExecBatch(const Schema& full_schema, + const Datum& partial, + Expression guarantee = literal(true)); + +/// Execute a scalar expression against the provided state and input ExecBatch. This +/// expression must be bound. +ARROW_EXPORT +Result ExecuteScalarExpression(const Expression&, const ExecBatch& input, + ExecContext* = NULLPTR); + +/// Convenience function for invoking against a RecordBatch +ARROW_EXPORT +Result ExecuteScalarExpression(const Expression&, const Schema& full_schema, + const Datum& partial_input, ExecContext* = NULLPTR); + +// Serialization + +ARROW_EXPORT +Result> Serialize(const Expression&); + +ARROW_EXPORT +Result Deserialize(std::shared_ptr); + +/// \defgroup expression-convenience Helpers for convenient expression creation +/// +/// @{ + +ARROW_EXPORT Expression project(std::vector values, + std::vector names); + +ARROW_EXPORT Expression equal(Expression lhs, Expression rhs); + +ARROW_EXPORT Expression not_equal(Expression lhs, Expression rhs); + +ARROW_EXPORT Expression less(Expression lhs, Expression rhs); + +ARROW_EXPORT Expression less_equal(Expression lhs, Expression rhs); + +ARROW_EXPORT Expression greater(Expression lhs, Expression rhs); + +ARROW_EXPORT Expression greater_equal(Expression lhs, Expression rhs); + +ARROW_EXPORT Expression is_null(Expression lhs, bool nan_is_null = false); + +ARROW_EXPORT Expression is_valid(Expression lhs); + +ARROW_EXPORT Expression and_(Expression lhs, Expression rhs); +ARROW_EXPORT Expression and_(const std::vector&); +ARROW_EXPORT Expression or_(Expression lhs, Expression rhs); +ARROW_EXPORT Expression or_(const std::vector&); +ARROW_EXPORT Expression not_(Expression operand); + +/// @} + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/function.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/function.h new file mode 100644 index 0000000000000000000000000000000000000000..399081e2a7371f7e39c7cc5da73af8f524ee9b99 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/function.h @@ -0,0 +1,410 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle. + +#pragma once + +#include +#include +#include + +#include "arrow/compute/kernel.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/datum.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/compare.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace compute { + +/// \addtogroup compute-functions +/// @{ + +/// \brief Contains the number of required arguments for the function. +/// +/// Naming conventions taken from https://en.wikipedia.org/wiki/Arity. +struct ARROW_EXPORT Arity { + /// \brief A function taking no arguments + static Arity Nullary() { return Arity(0, false); } + + /// \brief A function taking 1 argument + static Arity Unary() { return Arity(1, false); } + + /// \brief A function taking 2 arguments + static Arity Binary() { return Arity(2, false); } + + /// \brief A function taking 3 arguments + static Arity Ternary() { return Arity(3, false); } + + /// \brief A function taking a variable number of arguments + /// + /// \param[in] min_args the minimum number of arguments required when + /// invoking the function + static Arity VarArgs(int min_args = 0) { return Arity(min_args, true); } + + // NOTE: the 0-argument form (default constructor) is required for Cython + explicit Arity(int num_args = 0, bool is_varargs = false) + : num_args(num_args), is_varargs(is_varargs) {} + + /// The number of required arguments (or the minimum number for varargs + /// functions). + int num_args; + + /// If true, then the num_args is the minimum number of required arguments. + bool is_varargs = false; +}; + +struct ARROW_EXPORT FunctionDoc { + /// \brief A one-line summary of the function, using a verb. + /// + /// For example, "Add two numeric arrays or scalars". + std::string summary; + + /// \brief A detailed description of the function, meant to follow the summary. + std::string description; + + /// \brief Symbolic names (identifiers) for the function arguments. + /// + /// Some bindings may use this to generate nicer function signatures. + std::vector arg_names; + + // TODO add argument descriptions? + + /// \brief Name of the options class, if any. + std::string options_class; + + /// \brief Whether options are required for function execution + /// + /// If false, then either the function does not have an options class + /// or there is a usable default options value. + bool options_required; + + FunctionDoc() = default; + + FunctionDoc(std::string summary, std::string description, + std::vector arg_names, std::string options_class = "", + bool options_required = false) + : summary(std::move(summary)), + description(std::move(description)), + arg_names(std::move(arg_names)), + options_class(std::move(options_class)), + options_required(options_required) {} + + static const FunctionDoc& Empty(); +}; + +/// \brief An executor of a function with a preconfigured kernel +class ARROW_EXPORT FunctionExecutor { + public: + virtual ~FunctionExecutor() = default; + /// \brief Initialize or re-initialize the preconfigured kernel + /// + /// This method may be called zero or more times. Depending on how + /// the FunctionExecutor was obtained, it may already have been initialized. + virtual Status Init(const FunctionOptions* options = NULLPTR, + ExecContext* exec_ctx = NULLPTR) = 0; + /// \brief Execute the preconfigured kernel with arguments that must fit it + /// + /// The method requires the arguments be castable to the preconfigured types. + /// + /// \param[in] args Arguments to execute the function on + /// \param[in] length Length of arguments batch or -1 to default it. If the + /// function has no parameters, this determines the batch length, defaulting + /// to 0. Otherwise, if the function is scalar, this must equal the argument + /// batch's inferred length or be -1 to default to it. This is ignored for + /// vector functions. + virtual Result Execute(const std::vector& args, int64_t length = -1) = 0; +}; + +/// \brief Base class for compute functions. Function implementations contain a +/// collection of "kernels" which are implementations of the function for +/// specific argument types. Selecting a viable kernel for executing a function +/// is referred to as "dispatching". +class ARROW_EXPORT Function { + public: + /// \brief The kind of function, which indicates in what contexts it is + /// valid for use. + enum Kind { + /// A function that performs scalar data operations on whole arrays of + /// data. Can generally process Array or Scalar values. The size of the + /// output will be the same as the size (or broadcasted size, in the case + /// of mixing Array and Scalar inputs) of the input. + SCALAR, + + /// A function with array input and output whose behavior depends on the + /// values of the entire arrays passed, rather than the value of each scalar + /// value. + VECTOR, + + /// A function that computes scalar summary statistics from array input. + SCALAR_AGGREGATE, + + /// A function that computes grouped summary statistics from array input + /// and an array of group identifiers. + HASH_AGGREGATE, + + /// A function that dispatches to other functions and does not contain its + /// own kernels. + META + }; + + virtual ~Function() = default; + + /// \brief The name of the kernel. The registry enforces uniqueness of names. + const std::string& name() const { return name_; } + + /// \brief The kind of kernel, which indicates in what contexts it is valid + /// for use. + Function::Kind kind() const { return kind_; } + + /// \brief Contains the number of arguments the function requires, or if the + /// function accepts variable numbers of arguments. + const Arity& arity() const { return arity_; } + + /// \brief Return the function documentation + const FunctionDoc& doc() const { return doc_; } + + /// \brief Returns the number of registered kernels for this function. + virtual int num_kernels() const = 0; + + /// \brief Return a kernel that can execute the function given the exact + /// argument types (without implicit type casts). + /// + /// NB: This function is overridden in CastFunction. + virtual Result DispatchExact(const std::vector& types) const; + + /// \brief Return a best-match kernel that can execute the function given the argument + /// types, after implicit casts are applied. + /// + /// \param[in,out] values Argument types. An element may be modified to + /// indicate that the returned kernel only approximately matches the input + /// value descriptors; callers are responsible for casting inputs to the type + /// required by the kernel. + virtual Result DispatchBest(std::vector* values) const; + + /// \brief Get a function executor with a best-matching kernel + /// + /// The returned executor will by default work with the default FunctionOptions + /// and KernelContext. If you want to change that, call `FunctionExecutor::Init`. + virtual Result> GetBestExecutor( + std::vector inputs) const; + + /// \brief Execute the function eagerly with the passed input arguments with + /// kernel dispatch, batch iteration, and memory allocation details taken + /// care of. + /// + /// If the `options` pointer is null, then `default_options()` will be used. + /// + /// This function can be overridden in subclasses. + virtual Result Execute(const std::vector& args, + const FunctionOptions* options, ExecContext* ctx) const; + + virtual Result Execute(const ExecBatch& batch, const FunctionOptions* options, + ExecContext* ctx) const; + + /// \brief Returns the default options for this function. + /// + /// Whatever option semantics a Function has, implementations must guarantee + /// that default_options() is valid to pass to Execute as options. + const FunctionOptions* default_options() const { return default_options_; } + + virtual Status Validate() const; + + /// \brief Returns the pure property for this function. + /// + /// Impure functions are those that may return different results for the same + /// input arguments. For example, a function that returns a random number is + /// not pure. An expression containing only pure functions can be simplified by + /// pre-evaluating any sub-expressions that have constant arguments. + virtual bool is_pure() const { return true; } + + protected: + Function(std::string name, Function::Kind kind, const Arity& arity, FunctionDoc doc, + const FunctionOptions* default_options) + : name_(std::move(name)), + kind_(kind), + arity_(arity), + doc_(std::move(doc)), + default_options_(default_options) {} + + Status CheckArity(size_t num_args) const; + + std::string name_; + Function::Kind kind_; + Arity arity_; + const FunctionDoc doc_; + const FunctionOptions* default_options_ = NULLPTR; +}; + +namespace detail { + +template +class FunctionImpl : public Function { + public: + /// \brief Return pointers to current-available kernels for inspection + std::vector kernels() const { + std::vector result; + for (const auto& kernel : kernels_) { + result.push_back(&kernel); + } + return result; + } + + int num_kernels() const override { return static_cast(kernels_.size()); } + + protected: + FunctionImpl(std::string name, Function::Kind kind, const Arity& arity, FunctionDoc doc, + const FunctionOptions* default_options) + : Function(std::move(name), kind, arity, std::move(doc), default_options) {} + + std::vector kernels_; +}; + +/// \brief Look up a kernel in a function. If no Kernel is found, nullptr is returned. +ARROW_EXPORT +const Kernel* DispatchExactImpl(const Function* func, const std::vector&); + +/// \brief Return an error message if no Kernel is found. +ARROW_EXPORT +Status NoMatchingKernel(const Function* func, const std::vector&); + +} // namespace detail + +/// \brief A function that executes elementwise operations on arrays or +/// scalars, and therefore whose results generally do not depend on the order +/// of the values in the arguments. Accepts and returns arrays that are all of +/// the same size. These functions roughly correspond to the functions used in +/// SQL expressions. +class ARROW_EXPORT ScalarFunction : public detail::FunctionImpl { + public: + using KernelType = ScalarKernel; + + ScalarFunction(std::string name, const Arity& arity, FunctionDoc doc, + const FunctionOptions* default_options = NULLPTR, bool is_pure = true) + : detail::FunctionImpl(std::move(name), Function::SCALAR, arity, + std::move(doc), default_options), + is_pure_(is_pure) {} + + /// \brief Add a kernel with given input/output types, no required state + /// initialization, preallocation for fixed-width types, and default null + /// handling (intersect validity bitmaps of inputs). + Status AddKernel(std::vector in_types, OutputType out_type, + ArrayKernelExec exec, KernelInit init = NULLPTR, + std::shared_ptr constraint = NULLPTR); + + /// \brief Add a kernel (function implementation). Returns error if the + /// kernel's signature does not match the function's arity. + Status AddKernel(ScalarKernel kernel); + + /// \brief Returns the pure property for this function. + bool is_pure() const override { return is_pure_; } + + private: + const bool is_pure_; +}; + +/// \brief A function that executes general array operations that may yield +/// outputs of different sizes or have results that depend on the whole array +/// contents. These functions roughly correspond to the functions found in +/// non-SQL array languages like APL and its derivatives. +class ARROW_EXPORT VectorFunction : public detail::FunctionImpl { + public: + using KernelType = VectorKernel; + + VectorFunction(std::string name, const Arity& arity, FunctionDoc doc, + const FunctionOptions* default_options = NULLPTR) + : detail::FunctionImpl(std::move(name), Function::VECTOR, arity, + std::move(doc), default_options) {} + + /// \brief Add a simple kernel with given input/output types, no required + /// state initialization, no data preallocation, and no preallocation of the + /// validity bitmap. + Status AddKernel(std::vector in_types, OutputType out_type, + ArrayKernelExec exec, KernelInit init = NULLPTR); + + /// \brief Add a kernel (function implementation). Returns error if the + /// kernel's signature does not match the function's arity. + Status AddKernel(VectorKernel kernel); +}; + +class ARROW_EXPORT ScalarAggregateFunction + : public detail::FunctionImpl { + public: + using KernelType = ScalarAggregateKernel; + + ScalarAggregateFunction(std::string name, const Arity& arity, FunctionDoc doc, + const FunctionOptions* default_options = NULLPTR) + : detail::FunctionImpl(std::move(name), + Function::SCALAR_AGGREGATE, arity, + std::move(doc), default_options) {} + + /// \brief Add a kernel (function implementation). Returns error if the + /// kernel's signature does not match the function's arity. + Status AddKernel(ScalarAggregateKernel kernel); +}; + +class ARROW_EXPORT HashAggregateFunction + : public detail::FunctionImpl { + public: + using KernelType = HashAggregateKernel; + + HashAggregateFunction(std::string name, const Arity& arity, FunctionDoc doc, + const FunctionOptions* default_options = NULLPTR) + : detail::FunctionImpl(std::move(name), + Function::HASH_AGGREGATE, arity, + std::move(doc), default_options) {} + + /// \brief Add a kernel (function implementation). Returns error if the + /// kernel's signature does not match the function's arity. + Status AddKernel(HashAggregateKernel kernel); +}; + +/// \brief A function that dispatches to other functions. Must implement +/// MetaFunction::ExecuteImpl. +/// +/// For Array, ChunkedArray, and Scalar Datum kinds, may rely on the execution +/// of concrete Function types, but must handle other Datum kinds on its own. +class ARROW_EXPORT MetaFunction : public Function { + public: + int num_kernels() const override { return 0; } + + Result Execute(const std::vector& args, const FunctionOptions* options, + ExecContext* ctx) const override; + + Result Execute(const ExecBatch& batch, const FunctionOptions* options, + ExecContext* ctx) const override; + + protected: + virtual Result ExecuteImpl(const std::vector& args, + const FunctionOptions* options, + ExecContext* ctx) const = 0; + + MetaFunction(std::string name, const Arity& arity, FunctionDoc doc, + const FunctionOptions* default_options = NULLPTR) + : Function(std::move(name), Function::META, arity, std::move(doc), + default_options) {} +}; + +/// @} + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/function_options.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/function_options.h new file mode 100644 index 0000000000000000000000000000000000000000..88ec2fd2d0679b5c849549179aa652bec9b37b56 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/function_options.h @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle. + +#pragma once + +#include "arrow/compute/type_fwd.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace compute { + +/// \addtogroup compute-functions +/// @{ + +/// \brief Extension point for defining options outside libarrow (but +/// still within this project). +class ARROW_EXPORT FunctionOptionsType { + public: + virtual ~FunctionOptionsType() = default; + + virtual const char* type_name() const = 0; + virtual std::string Stringify(const FunctionOptions&) const = 0; + virtual bool Compare(const FunctionOptions&, const FunctionOptions&) const = 0; + virtual Result> Serialize(const FunctionOptions&) const; + virtual Result> Deserialize( + const Buffer& buffer) const; + virtual std::unique_ptr Copy(const FunctionOptions&) const = 0; +}; + +/// \brief Base class for specifying options configuring a function's behavior, +/// such as error handling. +class ARROW_EXPORT FunctionOptions : public util::EqualityComparable { + public: + virtual ~FunctionOptions() = default; + + const FunctionOptionsType* options_type() const { return options_type_; } + const char* type_name() const { return options_type()->type_name(); } + + bool Equals(const FunctionOptions& other) const; + std::string ToString() const; + std::unique_ptr Copy() const; + /// \brief Serialize an options struct to a buffer. + Result> Serialize() const; + /// \brief Deserialize an options struct from a buffer. + /// Note: this will only look for `type_name` in the default FunctionRegistry; + /// to use a custom FunctionRegistry, look up the FunctionOptionsType, then + /// call FunctionOptionsType::Deserialize(). + static Result> Deserialize( + const std::string& type_name, const Buffer& buffer); + + protected: + explicit FunctionOptions(const FunctionOptionsType* type) : options_type_(type) {} + const FunctionOptionsType* options_type_; +}; + +ARROW_EXPORT void PrintTo(const FunctionOptions&, std::ostream*); + +/// @} + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/initialize.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/initialize.h new file mode 100644 index 0000000000000000000000000000000000000000..db5e231325bab4c944e086078780ac7302008c77 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/initialize.h @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/compute/visibility.h" +#include "arrow/status.h" + +namespace arrow::compute { + +/// \brief Initialize the compute module. +/// +/// Register the compute kernel functions to be available on the +/// global FunctionRegistry. +/// This function will only be available if ARROW_COMPUTE is enabled. +ARROW_COMPUTE_EXPORT Status Initialize(); + +} // namespace arrow::compute diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/kernel.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0d4f9d6ff436de470801f061b4e66a5e58876286 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/kernel.h @@ -0,0 +1,772 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/compute/exec.h" +#include "arrow/datum.h" +#include "arrow/device_allocation_type_set.h" +#include "arrow/memory_pool.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +// macOS defines PREALLOCATE as a preprocessor macro in the header sys/vnode.h. +// No other BSD seems to do so. The name is used as an identifier in MemAllocation enum. +#if defined(__APPLE__) && defined(PREALLOCATE) +# undef PREALLOCATE +#endif + +namespace arrow { +namespace compute { + +class FunctionOptions; + +/// \brief Base class for opaque kernel-specific state. For example, if there +/// is some kind of initialization required. +struct ARROW_EXPORT KernelState { + virtual ~KernelState() = default; +}; + +/// \brief Context/state for the execution of a particular kernel. +class ARROW_EXPORT KernelContext { + public: + // Can pass optional backreference; not used consistently for the + // moment but will be made so in the future + explicit KernelContext(ExecContext* exec_ctx, const Kernel* kernel = NULLPTR) + : exec_ctx_(exec_ctx), kernel_(kernel) {} + + /// \brief Allocate buffer from the context's memory pool. The contents are + /// not initialized. + Result> Allocate(int64_t nbytes); + + /// \brief Allocate buffer for bitmap from the context's memory pool. Like + /// Allocate, the contents of the buffer are not initialized but the last + /// byte is preemptively zeroed to help avoid ASAN or valgrind issues. + Result> AllocateBitmap(int64_t num_bits); + + /// \brief Assign the active KernelState to be utilized for each stage of + /// kernel execution. Ownership and memory lifetime of the KernelState must + /// be minded separately. + void SetState(KernelState* state) { state_ = state; } + + // Set kernel that is being invoked since some kernel + // implementations will examine the kernel state. + void SetKernel(const Kernel* kernel) { kernel_ = kernel; } + + KernelState* state() { return state_; } + + /// \brief Configuration related to function execution that is to be shared + /// across multiple kernels. + ExecContext* exec_context() { return exec_ctx_; } + + /// \brief The memory pool to use for allocations. For now, it uses the + /// MemoryPool contained in the ExecContext used to create the KernelContext. + MemoryPool* memory_pool() { return exec_ctx_->memory_pool(); } + + const Kernel* kernel() const { return kernel_; } + + private: + ExecContext* exec_ctx_; + KernelState* state_ = NULLPTR; + const Kernel* kernel_ = NULLPTR; +}; + +/// \brief An type-checking interface to permit customizable validation rules +/// for use with InputType and KernelSignature. This is for scenarios where the +/// acceptance is not an exact type instance, such as a TIMESTAMP type for a +/// specific TimeUnit, but permitting any time zone. +struct ARROW_EXPORT TypeMatcher { + virtual ~TypeMatcher() = default; + + /// \brief Return true if this matcher accepts the data type. + virtual bool Matches(const DataType& type) const = 0; + + /// \brief A human-interpretable string representation of what the type + /// matcher checks for, usable when printing KernelSignature or formatting + /// error messages. + virtual std::string ToString() const = 0; + + /// \brief Return true if this TypeMatcher contains the same matching rule as + /// the other. Currently depends on RTTI. + virtual bool Equals(const TypeMatcher& other) const = 0; +}; + +namespace match { + +/// \brief Match any DataType instance having the same DataType::id. +ARROW_EXPORT std::shared_ptr SameTypeId(Type::type type_id); + +/// \brief Match any TimestampType instance having the same unit, but the time +/// zones can be different. +ARROW_EXPORT std::shared_ptr TimestampTypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr Time32TypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr Time64TypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr DurationTypeUnit(TimeUnit::type unit); + +// \brief Match any integer type +ARROW_EXPORT std::shared_ptr Integer(); + +// Match types using 32-bit varbinary representation +ARROW_EXPORT std::shared_ptr BinaryLike(); + +// Match types using 64-bit varbinary representation +ARROW_EXPORT std::shared_ptr LargeBinaryLike(); + +// Match any fixed binary type +ARROW_EXPORT std::shared_ptr FixedSizeBinaryLike(); + +// \brief Match any primitive type (boolean or any type representable as a C +// Type) +ARROW_EXPORT std::shared_ptr Primitive(); + +// \brief Match any integer type that can be used as run-end in run-end encoded +// arrays +ARROW_EXPORT std::shared_ptr RunEndInteger(); + +/// \brief Match run-end encoded types that use any valid run-end type and +/// encode specific value types +/// +/// @param[in] value_type_matcher a matcher that is applied to the values field +ARROW_EXPORT std::shared_ptr RunEndEncoded( + std::shared_ptr value_type_matcher); + +/// \brief Match run-end encoded types that use any valid run-end type and +/// encode specific value types +/// +/// @param[in] value_type_id a type id that the type of the values field should match +ARROW_EXPORT std::shared_ptr RunEndEncoded(Type::type value_type_id); + +/// \brief Match run-end encoded types that encode specific run-end and value types +/// +/// @param[in] run_end_type_matcher a matcher that is applied to the run_ends field +/// @param[in] value_type_matcher a matcher that is applied to the values field +ARROW_EXPORT std::shared_ptr RunEndEncoded( + std::shared_ptr run_end_type_matcher, + std::shared_ptr value_type_matcher); + +} // namespace match + +/// \brief An object used for type-checking arguments to be passed to a kernel +/// and stored in a KernelSignature. The type-checking rule can be supplied +/// either with an exact DataType instance or a custom TypeMatcher. +class ARROW_EXPORT InputType { + public: + /// \brief The kind of type-checking rule that the InputType contains. + enum Kind { + /// \brief Accept any value type. + ANY_TYPE, + + /// \brief A fixed arrow::DataType and will only exact match having this + /// exact type (e.g. same TimestampType unit, same decimal scale and + /// precision, or same nested child types). + EXACT_TYPE, + + /// \brief Uses a TypeMatcher implementation to check the type. + USE_TYPE_MATCHER + }; + + /// \brief Accept any value type + InputType() : kind_(ANY_TYPE) {} + + /// \brief Accept an exact value type. + InputType(std::shared_ptr type) // NOLINT implicit construction + : kind_(EXACT_TYPE), type_(std::move(type)) {} + + /// \brief Use the passed TypeMatcher to type check. + InputType(std::shared_ptr type_matcher) // NOLINT implicit construction + : kind_(USE_TYPE_MATCHER), type_matcher_(std::move(type_matcher)) {} + + /// \brief Match any type with the given Type::type. Uses a TypeMatcher for + /// its implementation. + InputType(Type::type type_id) // NOLINT implicit construction + : InputType(match::SameTypeId(type_id)) {} + + InputType(const InputType& other) { CopyInto(other); } + + void operator=(const InputType& other) { CopyInto(other); } + + InputType(InputType&& other) { MoveInto(std::forward(other)); } + + void operator=(InputType&& other) { MoveInto(std::forward(other)); } + + // \brief Match any input (array, scalar of any type) + static InputType Any() { return InputType(); } + + /// \brief Return true if this input type matches the same type cases as the + /// other. + bool Equals(const InputType& other) const; + + bool operator==(const InputType& other) const { return this->Equals(other); } + + bool operator!=(const InputType& other) const { return !(*this == other); } + + /// \brief Return hash code. + size_t Hash() const; + + /// \brief Render a human-readable string representation. + std::string ToString() const; + + /// \brief Return true if the Datum matches this argument kind in + /// type (and only allows scalar or array-like Datums). + bool Matches(const Datum& value) const; + + /// \brief Return true if the type matches this InputType + bool Matches(const DataType& type) const; + + /// \brief The type matching rule that this InputType uses. + Kind kind() const { return kind_; } + + /// \brief For InputType::EXACT_TYPE kind, the exact type that this InputType + /// must match. Otherwise this function should not be used and will assert in + /// debug builds. + const std::shared_ptr& type() const; + + /// \brief For InputType::USE_TYPE_MATCHER, the TypeMatcher to be used for + /// checking the type of a value. Otherwise this function should not be used + /// and will assert in debug builds. + const TypeMatcher& type_matcher() const; + + private: + void CopyInto(const InputType& other) { + this->kind_ = other.kind_; + this->type_ = other.type_; + this->type_matcher_ = other.type_matcher_; + } + + void MoveInto(InputType&& other) { + this->kind_ = other.kind_; + this->type_ = std::move(other.type_); + this->type_matcher_ = std::move(other.type_matcher_); + } + + Kind kind_; + + // For EXACT_TYPE Kind + std::shared_ptr type_; + + // For USE_TYPE_MATCHER Kind + std::shared_ptr type_matcher_; +}; + +/// \brief Container to capture both exact and input-dependent output types. +class ARROW_EXPORT OutputType { + public: + /// \brief An enum indicating whether the value type is an invariant fixed + /// value or one that's computed by a kernel-defined resolver function. + enum ResolveKind { FIXED, COMPUTED }; + + /// Type resolution function. Given input types, return output type. This + /// function MAY may use the kernel state to decide the output type based on + /// the FunctionOptions. + /// + /// This function SHOULD _not_ be used to check for arity, that is to be + /// performed one or more layers above. + using Resolver = + std::function(KernelContext*, const std::vector&)>; + + /// \brief Output an exact type + OutputType(std::shared_ptr type) // NOLINT implicit construction + : kind_(FIXED), type_(std::move(type)) {} + + /// \brief Output a computed type depending on actual input types + template + OutputType(Fn resolver) // NOLINT implicit construction + : kind_(COMPUTED), resolver_(std::move(resolver)) {} + + OutputType(const OutputType& other) { + this->kind_ = other.kind_; + this->type_ = other.type_; + this->resolver_ = other.resolver_; + } + + OutputType(OutputType&& other) { + this->kind_ = other.kind_; + this->type_ = std::move(other.type_); + this->resolver_ = other.resolver_; + } + + OutputType& operator=(const OutputType&) = default; + OutputType& operator=(OutputType&&) = default; + + /// \brief Return the type of the expected output value of the kernel given + /// the input argument types. The resolver may make use of state information + /// kept in the KernelContext. + Result Resolve(KernelContext* ctx, + const std::vector& args) const; + + /// \brief The exact output value type for the FIXED kind. + const std::shared_ptr& type() const; + + /// \brief For use with COMPUTED resolution strategy. It may be more + /// convenient to invoke this with OutputType::Resolve returned from this + /// method. + const Resolver& resolver() const; + + /// \brief Render a human-readable string representation. + std::string ToString() const; + + /// \brief Return the kind of type resolution of this output type, whether + /// fixed/invariant or computed by a resolver. + ResolveKind kind() const { return kind_; } + + private: + ResolveKind kind_; + + // For FIXED resolution + std::shared_ptr type_; + + // For COMPUTED resolution + Resolver resolver_ = NULLPTR; +}; + +/// \brief Additional constraints to apply to the input types of a kernel when matching a +/// specific kernel signature. +class ARROW_EXPORT MatchConstraint { + public: + virtual ~MatchConstraint() = default; + + /// \brief Return true if the input types satisfy the constraint. + virtual bool Matches(const std::vector& types) const = 0; + + /// \brief Convenience function to create a MatchConstraint from a match function. + static std::shared_ptr Make( + std::function&)> matches); +}; + +/// \brief Constraint that all input types are decimal types and have the same scale. +ARROW_EXPORT std::shared_ptr DecimalsHaveSameScale(); + +/// \brief Holds the input types, optional match constraint and output type of the kernel. +/// +/// VarArgs functions with minimum N arguments should pass up to N input types to be +/// used to validate the input types of a function invocation. The first N-1 types +/// will be matched against the first N-1 arguments, and the last type will be +/// matched against the remaining arguments. +class ARROW_EXPORT KernelSignature { + public: + KernelSignature(std::vector in_types, OutputType out_type, + bool is_varargs = false, + std::shared_ptr constraint = NULLPTR); + + /// \brief Convenience ctor since make_shared can be awkward + static std::shared_ptr Make( + std::vector in_types, OutputType out_type, bool is_varargs = false, + std::shared_ptr constraint = NULLPTR); + + /// \brief Return true if the signature is compatible with the list of input + /// value descriptors and satisfies the match constraint, if any. + bool MatchesInputs(const std::vector& types) const; + + /// \brief Returns true if the input types of each signature are + /// equal. Well-formed functions should have a deterministic output type + /// given input types, but currently it is the responsibility of the + /// developer to ensure this. + bool Equals(const KernelSignature& other) const; + + bool operator==(const KernelSignature& other) const { return this->Equals(other); } + + bool operator!=(const KernelSignature& other) const { return !(*this == other); } + + /// \brief Compute a hash code for the signature + size_t Hash() const; + + /// \brief The input types for the kernel. For VarArgs functions, this should + /// generally contain a single validator to use for validating all of the + /// function arguments. + const std::vector& in_types() const { return in_types_; } + + /// \brief The output type for the kernel. Use Resolve to return the + /// exact output given input argument types, since many kernels' + /// output types depend on their input types (or their type + /// metadata). + const OutputType& out_type() const { return out_type_; } + + /// \brief Render a human-readable string representation + std::string ToString() const; + + bool is_varargs() const { return is_varargs_; } + + private: + std::vector in_types_; + OutputType out_type_; + bool is_varargs_; + std::shared_ptr constraint_; + + // For caching the hash code after it's computed the first time + mutable uint64_t hash_code_; +}; + +/// \brief A function may contain multiple variants of a kernel for a given +/// type combination for different SIMD levels. Based on the active system's +/// CPU info or the user's preferences, we can elect to use one over the other. +struct SimdLevel { + enum type { NONE = 0, SSE4_2, AVX, AVX2, AVX512, NEON, MAX }; +}; + +/// \brief The strategy to use for propagating or otherwise populating the +/// validity bitmap of a kernel output. +struct NullHandling { + enum type { + /// Compute the output validity bitmap by intersecting the validity bitmaps + /// of the arguments using bitwise-and operations. This means that values + /// in the output are valid/non-null only if the corresponding values in + /// all input arguments were valid/non-null. Kernel generally need not + /// touch the bitmap thereafter, but a kernel's exec function is permitted + /// to alter the bitmap after the null intersection is computed if it needs + /// to. + INTERSECTION, + + /// Kernel expects a pre-allocated buffer to write the result bitmap + /// into. The preallocated memory is not zeroed (except for the last byte), + /// so the kernel should ensure to completely populate the bitmap. + COMPUTED_PREALLOCATE, + + /// Kernel allocates and sets the validity bitmap of the output. + COMPUTED_NO_PREALLOCATE, + + /// Kernel output is never null and a validity bitmap does not need to be + /// allocated. + OUTPUT_NOT_NULL + }; +}; + +/// \brief The preference for memory preallocation of fixed-width type outputs +/// in kernel execution. +struct MemAllocation { + enum type { + // For data types that support pre-allocation (i.e. fixed-width), the + // kernel expects to be provided a pre-allocated data buffer to write + // into. Non-fixed-width types must always allocate their own data + // buffers. The allocation made for the same length as the execution batch, + // so vector kernels yielding differently sized output should not use this. + // + // It is valid for the data to not be preallocated but the validity bitmap + // is (or is computed using the intersection/bitwise-and method). + // + // For variable-size output types like BinaryType or StringType, or for + // nested types, this option has no effect. + PREALLOCATE, + + // The kernel is responsible for allocating its own data buffer for + // fixed-width type outputs. + NO_PREALLOCATE + }; +}; + +struct Kernel; + +/// \brief Arguments to pass to an KernelInit function. A struct is used to help +/// avoid API breakage should the arguments passed need to be expanded. +struct KernelInitArgs { + /// \brief A pointer to the kernel being initialized. The init function may + /// depend on the kernel's KernelSignature or other data contained there. + const Kernel* kernel; + + /// \brief The types of the input arguments that the kernel is + /// about to be executed against. + const std::vector& inputs; + + /// \brief Opaque options specific to this kernel. May be nullptr for functions + /// that do not require options. + const FunctionOptions* options; +}; + +/// \brief Common initializer function for all kernel types. +using KernelInit = std::function>( + KernelContext*, const KernelInitArgs&)>; + +/// \brief Base type for kernels. Contains the function signature and +/// optionally the state initialization function, along with some common +/// attributes +struct ARROW_EXPORT Kernel { + Kernel() = default; + + Kernel(std::shared_ptr sig, KernelInit init) + : signature(std::move(sig)), init(std::move(init)) {} + + Kernel(std::vector in_types, OutputType out_type, KernelInit init) + : Kernel(KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init)) {} + + /// \brief The "signature" of the kernel containing the InputType input + /// argument validators and OutputType output type resolver. + std::shared_ptr signature; + + /// \brief Create a new KernelState for invocations of this kernel, e.g. to + /// set up any options or state relevant for execution. + KernelInit init; + + /// \brief Create a vector of new KernelState for invocations of this kernel. + static Status InitAll(KernelContext*, const KernelInitArgs&, + std::vector>*); + + /// \brief Indicates whether execution can benefit from parallelization + /// (splitting large chunks into smaller chunks and using multiple + /// threads). Some kernels may not support parallel execution at + /// all. Synchronization and concurrency-related issues are currently the + /// responsibility of the Kernel's implementation. + bool parallelizable = true; + + /// \brief Indicates the level of SIMD instruction support in the host CPU is + /// required to use the function. The intention is for functions to be able to + /// contain multiple kernels with the same signature but different levels of SIMD, + /// so that the most optimized kernel supported on a host's processor can be chosen. + SimdLevel::type simd_level = SimdLevel::NONE; + + // Additional kernel-specific data + std::shared_ptr data; +}; + +/// \brief The scalar kernel execution API that must be implemented for SCALAR +/// kernel types. This includes both stateless and stateful kernels. Kernels +/// depending on some execution state access that state via subclasses of +/// KernelState set on the KernelContext object. Implementations should +/// endeavor to write into pre-allocated memory if they are able, though for +/// some kernels (e.g. in cases when a builder like StringBuilder) must be +/// employed this may not be possible. +using ArrayKernelExec = Status (*)(KernelContext*, const ExecSpan&, ExecResult*); + +/// \brief Kernel data structure for implementations of ScalarFunction. In +/// addition to the members found in Kernel, contains the null handling +/// and memory pre-allocation preferences. +struct ARROW_EXPORT ScalarKernel : public Kernel { + ScalarKernel() = default; + + ScalarKernel(std::shared_ptr sig, ArrayKernelExec exec, + KernelInit init = NULLPTR) + : Kernel(std::move(sig), init), exec(exec) {} + + ScalarKernel(std::vector in_types, OutputType out_type, ArrayKernelExec exec, + KernelInit init = NULLPTR) + : Kernel(std::move(in_types), std::move(out_type), std::move(init)), exec(exec) {} + + /// \brief Perform a single invocation of this kernel. Depending on the + /// implementation, it may only write into preallocated memory, while in some + /// cases it will allocate its own memory. Any required state is managed + /// through the KernelContext. + ArrayKernelExec exec; + + /// \brief Writing execution results into larger contiguous allocations + /// requires that the kernel be able to write into sliced output ArrayData*, + /// including sliced output validity bitmaps. Some kernel implementations may + /// not be able to do this, so setting this to false disables this + /// functionality. + bool can_write_into_slices = true; + + // For scalar functions preallocated data and intersecting arg validity + // bitmaps is a reasonable default + NullHandling::type null_handling = NullHandling::INTERSECTION; + MemAllocation::type mem_allocation = MemAllocation::PREALLOCATE; +}; + +// ---------------------------------------------------------------------- +// VectorKernel (for VectorFunction) + +/// \brief Kernel data structure for implementations of VectorFunction. In +/// contains an optional finalizer function, the null handling and memory +/// pre-allocation preferences (which have different defaults from +/// ScalarKernel), and some other execution-related options. +struct ARROW_EXPORT VectorKernel : public Kernel { + /// \brief See VectorKernel::finalize member for usage + using FinalizeFunc = std::function*)>; + + /// \brief Function for executing a stateful VectorKernel against a + /// ChunkedArray input. Does not need to be defined for all VectorKernels + using ChunkedExec = Status (*)(KernelContext*, const ExecBatch&, Datum* out); + + VectorKernel() = default; + + VectorKernel(std::vector in_types, OutputType out_type, ArrayKernelExec exec, + KernelInit init = NULLPTR, FinalizeFunc finalize = NULLPTR) + : Kernel(std::move(in_types), std::move(out_type), std::move(init)), + exec(exec), + finalize(std::move(finalize)) {} + + VectorKernel(std::shared_ptr sig, ArrayKernelExec exec, + KernelInit init = NULLPTR, FinalizeFunc finalize = NULLPTR) + : Kernel(std::move(sig), std::move(init)), + exec(exec), + finalize(std::move(finalize)) {} + + /// \brief Perform a single invocation of this kernel. Any required state is + /// managed through the KernelContext. + ArrayKernelExec exec; + + /// \brief Execute the kernel on a ChunkedArray. Does not need to be defined + ChunkedExec exec_chunked = NULLPTR; + + /// \brief For VectorKernel, convert intermediate results into finalized + /// results. Mutates input argument. Some kernels may accumulate state + /// (example: hashing-related functions) through processing chunked inputs, and + /// then need to attach some accumulated state to each of the outputs of + /// processing each chunk of data. + FinalizeFunc finalize; + + /// Since vector kernels generally are implemented rather differently from + /// scalar/elementwise kernels (and they may not even yield arrays of the same + /// size), so we make the developer opt-in to any memory preallocation rather + /// than having to turn it off. + NullHandling::type null_handling = NullHandling::COMPUTED_NO_PREALLOCATE; + MemAllocation::type mem_allocation = MemAllocation::NO_PREALLOCATE; + + /// \brief Writing execution results into larger contiguous allocations + /// requires that the kernel be able to write into sliced output ArrayData*, + /// including sliced output validity bitmaps. Some kernel implementations may + /// not be able to do this, so setting this to false disables this + /// functionality. + bool can_write_into_slices = true; + + /// Some vector kernels can do chunkwise execution using ExecSpanIterator, + /// in some cases accumulating some state. Other kernels (like Take) need to + /// be passed whole arrays and don't work on ChunkedArray inputs + bool can_execute_chunkwise = true; + + /// Some kernels (like unique and value_counts) yield non-chunked output from + /// chunked-array inputs. This option controls how the results are boxed when + /// returned from ExecVectorFunction + /// + /// true -> ChunkedArray + /// false -> Array + bool output_chunked = true; +}; + +// ---------------------------------------------------------------------- +// ScalarAggregateKernel (for ScalarAggregateFunction) + +using ScalarAggregateConsume = Status (*)(KernelContext*, const ExecSpan&); +using ScalarAggregateMerge = Status (*)(KernelContext*, KernelState&&, KernelState*); +// Finalize returns Datum to permit multiple return values +using ScalarAggregateFinalize = Status (*)(KernelContext*, Datum*); + +/// \brief Kernel data structure for implementations of +/// ScalarAggregateFunction. The four necessary components of an aggregation +/// kernel are the init, consume, merge, and finalize functions. +/// +/// * init: creates a new KernelState for a kernel. +/// * consume: processes an ExecSpan and updates the KernelState found in the +/// KernelContext. +/// * merge: combines one KernelState with another. +/// * finalize: produces the end result of the aggregation using the +/// KernelState in the KernelContext. +struct ARROW_EXPORT ScalarAggregateKernel : public Kernel { + ScalarAggregateKernel(std::shared_ptr sig, KernelInit init, + ScalarAggregateConsume consume, ScalarAggregateMerge merge, + ScalarAggregateFinalize finalize, const bool ordered) + : Kernel(std::move(sig), std::move(init)), + consume(consume), + merge(merge), + finalize(finalize), + ordered(ordered) {} + + ScalarAggregateKernel(std::vector in_types, OutputType out_type, + KernelInit init, ScalarAggregateConsume consume, + ScalarAggregateMerge merge, ScalarAggregateFinalize finalize, + const bool ordered) + : ScalarAggregateKernel( + KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init), consume, merge, finalize, ordered) {} + + /// \brief Merge a vector of KernelStates into a single KernelState. + /// The merged state will be returned and will be set on the KernelContext. + static Result> MergeAll( + const ScalarAggregateKernel* kernel, KernelContext* ctx, + std::vector> states); + + ScalarAggregateConsume consume; + ScalarAggregateMerge merge; + ScalarAggregateFinalize finalize; + /// \brief Whether this kernel requires ordering + /// Some aggregations, such as, "first", requires some kind of input order. The + /// order can be implicit, e.g., the order of the input data, or explicit, e.g. + /// the ordering specified with a window aggregation. + /// The caller of the aggregate kernel is responsible for passing data in some + /// defined order to the kernel. The flag here is a way for the kernel to tell + /// the caller that data passed to the kernel must be defined in some order. + bool ordered = false; +}; + +// ---------------------------------------------------------------------- +// HashAggregateKernel (for HashAggregateFunction) + +using HashAggregateResize = Status (*)(KernelContext*, int64_t); +using HashAggregateConsume = Status (*)(KernelContext*, const ExecSpan&); +using HashAggregateMerge = Status (*)(KernelContext*, KernelState&&, const ArrayData&); + +// Finalize returns Datum to permit multiple return values +using HashAggregateFinalize = Status (*)(KernelContext*, Datum*); + +/// \brief Kernel data structure for implementations of +/// HashAggregateFunction. The four necessary components of an aggregation +/// kernel are the init, consume, merge, and finalize functions. +/// +/// * init: creates a new KernelState for a kernel. +/// * resize: ensure that the KernelState can accommodate the specified number of groups. +/// * consume: processes an ExecSpan (which includes the argument as well +/// as an array of group identifiers) and updates the KernelState found in the +/// KernelContext. +/// * merge: combines one KernelState with another. +/// * finalize: produces the end result of the aggregation using the +/// KernelState in the KernelContext. +struct ARROW_EXPORT HashAggregateKernel : public Kernel { + HashAggregateKernel() = default; + + HashAggregateKernel(std::shared_ptr sig, KernelInit init, + HashAggregateResize resize, HashAggregateConsume consume, + HashAggregateMerge merge, HashAggregateFinalize finalize, + const bool ordered) + : Kernel(std::move(sig), std::move(init)), + resize(resize), + consume(consume), + merge(merge), + finalize(finalize), + ordered(ordered) {} + + HashAggregateKernel(std::vector in_types, OutputType out_type, + KernelInit init, HashAggregateConsume consume, + HashAggregateResize resize, HashAggregateMerge merge, + HashAggregateFinalize finalize, const bool ordered) + : HashAggregateKernel( + KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init), resize, consume, merge, finalize, ordered) {} + + HashAggregateResize resize; + HashAggregateConsume consume; + HashAggregateMerge merge; + HashAggregateFinalize finalize; + /// @brief whether the summarizer requires ordering + /// This is similar to ScalarAggregateKernel. See ScalarAggregateKernel + /// for detailed doc of this variable. + bool ordered = false; +}; + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/ordering.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/ordering.h new file mode 100644 index 0000000000000000000000000000000000000000..61caa2b570dd31dc988d34406f9b05c3573333e2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/ordering.h @@ -0,0 +1,120 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/type.h" +#include "arrow/util/compare.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace compute { + +enum class SortOrder { + /// Arrange values in increasing order + Ascending, + /// Arrange values in decreasing order + Descending, +}; + +enum class NullPlacement { + /// Place nulls and NaNs before any non-null values. + /// NaNs will come after nulls. + AtStart, + /// Place nulls and NaNs after any non-null values. + /// NaNs will come before nulls. + AtEnd, +}; + +/// \brief One sort key for PartitionNthIndices (TODO) and SortIndices +class ARROW_EXPORT SortKey : public util::EqualityComparable { + public: + explicit SortKey(FieldRef target, SortOrder order = SortOrder::Ascending) + : target(std::move(target)), order(order) {} + + bool Equals(const SortKey& other) const; + std::string ToString() const; + + /// A FieldRef targeting the sort column. + FieldRef target; + /// How to order by this sort key. + SortOrder order; +}; + +class ARROW_EXPORT Ordering : public util::EqualityComparable { + public: + Ordering(std::vector sort_keys, + NullPlacement null_placement = NullPlacement::AtStart) + : sort_keys_(std::move(sort_keys)), null_placement_(null_placement) {} + /// true if data ordered by other is also ordered by this + /// + /// For example, if data is ordered by [a, b, c] then it is also ordered + /// by [a, b] but not by [b, c] or [a, b, c, d]. + /// + /// [a, b].IsSuborderOf([a, b, c]) - true + /// [a, b, c].IsSuborderOf([a, b, c]) - true + /// [b, c].IsSuborderOf([a, b, c]) - false + /// [a, b, c, d].IsSuborderOf([a, b, c]) - false + /// + /// The implicit ordering is not a suborder of any other ordering and + /// no other ordering is a suborder of it. The implicit ordering is not a + /// suborder of itself. + /// + /// The unordered ordering is a suborder of all other orderings but no + /// other ordering is a suborder of it. The unordered ordering is a suborder + /// of itself. + /// + /// The unordered ordering is a suborder of the implicit ordering. + bool IsSuborderOf(const Ordering& other) const; + + bool Equals(const Ordering& other) const; + std::string ToString() const; + + bool is_implicit() const { return is_implicit_; } + bool is_unordered() const { return !is_implicit_ && sort_keys_.empty(); } + + const std::vector& sort_keys() const { return sort_keys_; } + NullPlacement null_placement() const { return null_placement_; } + + static const Ordering& Implicit() { + static const Ordering kImplicit(true); + return kImplicit; + } + + static const Ordering& Unordered() { + static const Ordering kUnordered(false); + // It is also possible to get an unordered ordering by passing in an empty vector + // using the normal constructor. This is ok and useful when ordering comes from user + // input. + return kUnordered; + } + + private: + explicit Ordering(bool is_implicit) + : null_placement_(NullPlacement::AtStart), is_implicit_(is_implicit) {} + /// Column key(s) to order by and how to order by these sort keys. + std::vector sort_keys_; + /// Whether nulls and NaNs are placed at the start or at the end + NullPlacement null_placement_; + bool is_implicit_ = false; +}; + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/registry.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/registry.h new file mode 100644 index 0000000000000000000000000000000000000000..f31c4c1ba5920626578a4e4170e3cd2d28288545 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/registry.h @@ -0,0 +1,126 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle + +#pragma once + +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace compute { + +class Function; +class FunctionOptionsType; + +/// \brief A mutable central function registry for built-in functions as well +/// as user-defined functions. Functions are implementations of +/// arrow::compute::Function. +/// +/// Generally, each function contains kernels which are implementations of a +/// function for a specific argument signature. After looking up a function in +/// the registry, one can either execute it eagerly with Function::Execute or +/// use one of the function's dispatch methods to pick a suitable kernel for +/// lower-level function execution. +class ARROW_EXPORT FunctionRegistry { + public: + ~FunctionRegistry(); + + /// \brief Construct a new registry. + /// + /// Most users only need to use the global registry. + static std::unique_ptr Make(); + + /// \brief Construct a new nested registry with the given parent. + /// + /// Most users only need to use the global registry. The returned registry never changes + /// its parent, even when an operation allows overwriting. + static std::unique_ptr Make(FunctionRegistry* parent); + + /// \brief Check whether a new function can be added to the registry. + /// + /// \returns Status::KeyError if a function with the same name is already registered. + Status CanAddFunction(std::shared_ptr function, bool allow_overwrite = false); + + /// \brief Add a new function to the registry. + /// + /// \returns Status::KeyError if a function with the same name is already registered. + Status AddFunction(std::shared_ptr function, bool allow_overwrite = false); + + /// \brief Check whether an alias can be added for the given function name. + /// + /// \returns Status::KeyError if the function with the given name is not registered. + Status CanAddAlias(const std::string& target_name, const std::string& source_name); + + /// \brief Add alias for the given function name. + /// + /// \returns Status::KeyError if the function with the given name is not registered. + Status AddAlias(const std::string& target_name, const std::string& source_name); + + /// \brief Check whether a new function options type can be added to the registry. + /// + /// \return Status::KeyError if a function options type with the same name is already + /// registered. + Status CanAddFunctionOptionsType(const FunctionOptionsType* options_type, + bool allow_overwrite = false); + + /// \brief Add a new function options type to the registry. + /// + /// \returns Status::KeyError if a function options type with the same name is already + /// registered. + Status AddFunctionOptionsType(const FunctionOptionsType* options_type, + bool allow_overwrite = false); + + /// \brief Retrieve a function by name from the registry. + Result> GetFunction(const std::string& name) const; + + /// \brief Return vector of all entry names in the registry. + /// + /// Helpful for displaying a manifest of available functions. + std::vector GetFunctionNames() const; + + /// \brief Retrieve a function options type by name from the registry. + Result GetFunctionOptionsType( + const std::string& name) const; + + /// \brief The number of currently registered functions. + int num_functions() const; + + /// \brief The cast function object registered in AddFunction. + /// + /// Helpful for get cast function as needed. + const Function* cast_function() const; + + private: + FunctionRegistry(); + + // Use PIMPL pattern to not have std::unordered_map here + class FunctionRegistryImpl; + std::unique_ptr impl_; + + explicit FunctionRegistry(FunctionRegistryImpl* impl); +}; + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/type_fwd.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..016d97a0dbc2b3b77be0b07e7effca3669439eb8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/type_fwd.h @@ -0,0 +1,59 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/util/visibility.h" + +namespace arrow { + +struct Datum; +struct TypeHolder; + +namespace compute { + +class Function; +class ScalarAggregateFunction; +class FunctionExecutor; +class FunctionOptions; +class FunctionRegistry; + +/// \brief Return the process-global function registry. +// Defined in registry.cc +ARROW_EXPORT FunctionRegistry* GetFunctionRegistry(); + +class CastOptions; + +struct ExecBatch; +class ExecContext; +struct ExecValue; +class KernelContext; + +struct Kernel; +struct ScalarKernel; +struct ScalarAggregateKernel; +struct VectorKernel; + +struct KernelState; + +class Expression; + +ARROW_EXPORT ExecContext* default_exec_context(); +ARROW_EXPORT ExecContext* threaded_exec_context(); + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/util.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/util.h new file mode 100644 index 0000000000000000000000000000000000000000..51a24b50fe60d4e22a9de02111568efd7f9cf334 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/util.h @@ -0,0 +1,221 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/compute/expression.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/compute/visibility.h" +#include "arrow/result.h" +#include "arrow/util/cpu_info.h" +#include "arrow/util/simd.h" + +#if defined(__clang__) || defined(__GNUC__) +# define BYTESWAP(x) __builtin_bswap64(x) +# define ROTL(x, n) (((x) << (n)) | ((x) >> ((-n) & 31))) +# define ROTL64(x, n) (((x) << (n)) | ((x) >> ((-n) & 63))) +#elif defined(_MSC_VER) +# include +# define BYTESWAP(x) _byteswap_uint64(x) +# define ROTL(x, n) _rotl((x), (n)) +# define ROTL64(x, n) _rotl64((x), (n)) +#endif + +namespace arrow { +namespace util { + +// Some platforms typedef int64_t as long int instead of long long int, +// which breaks the _mm256_i64gather_epi64 and _mm256_i32gather_epi64 intrinsics +// which need long long. +// We use the cast to the type below in these intrinsics to make the code +// compile in all cases. +// +using int64_for_gather_t = const long long int; // NOLINT runtime-int + +// All MiniBatch... classes use TempVectorStack for vector allocations and can +// only work with vectors up to 1024 elements. +// +// They should only be allocated on the stack to guarantee the right sequence +// of allocation and deallocation of vectors from TempVectorStack. +// +class MiniBatch { + public: + static constexpr int kLogMiniBatchLength = 10; + static constexpr int kMiniBatchLength = 1 << kLogMiniBatchLength; +}; + +namespace bit_util { + +ARROW_COMPUTE_EXPORT void bits_to_indexes(int bit_to_search, int64_t hardware_flags, + const int num_bits, const uint8_t* bits, + int* num_indexes, uint16_t* indexes, + int bit_offset = 0); + +ARROW_COMPUTE_EXPORT void bits_filter_indexes(int bit_to_search, int64_t hardware_flags, + const int num_bits, const uint8_t* bits, + const uint16_t* input_indexes, + int* num_indexes, uint16_t* indexes, + int bit_offset = 0); + +// Input and output indexes may be pointing to the same data (in-place filtering). +ARROW_COMPUTE_EXPORT void bits_split_indexes(int64_t hardware_flags, const int num_bits, + const uint8_t* bits, int* num_indexes_bit0, + uint16_t* indexes_bit0, + uint16_t* indexes_bit1, int bit_offset = 0); + +// Bit 1 is replaced with byte 0xFF. +ARROW_COMPUTE_EXPORT void bits_to_bytes(int64_t hardware_flags, const int num_bits, + const uint8_t* bits, uint8_t* bytes, + int bit_offset = 0); + +// Return highest bit of each byte. +ARROW_COMPUTE_EXPORT void bytes_to_bits(int64_t hardware_flags, const int num_bits, + const uint8_t* bytes, uint8_t* bits, + int bit_offset = 0); + +ARROW_COMPUTE_EXPORT bool are_all_bytes_zero(int64_t hardware_flags, const uint8_t* bytes, + uint32_t num_bytes); + +#if defined(ARROW_HAVE_RUNTIME_AVX2) && defined(ARROW_HAVE_RUNTIME_BMI2) +// The functions below use BMI2 instructions, be careful before calling! + +namespace avx2 { +ARROW_COMPUTE_EXPORT void bits_filter_indexes_avx2(int bit_to_search, const int num_bits, + const uint8_t* bits, + const uint16_t* input_indexes, + int* num_indexes, uint16_t* indexes); +ARROW_COMPUTE_EXPORT void bits_to_indexes_avx2(int bit_to_search, const int num_bits, + const uint8_t* bits, int* num_indexes, + uint16_t* indexes, + uint16_t base_index = 0); +ARROW_COMPUTE_EXPORT void bits_to_bytes_avx2(const int num_bits, const uint8_t* bits, + uint8_t* bytes); +ARROW_COMPUTE_EXPORT void bytes_to_bits_avx2(const int num_bits, const uint8_t* bytes, + uint8_t* bits); +ARROW_COMPUTE_EXPORT bool are_all_bytes_zero_avx2(const uint8_t* bytes, + uint32_t num_bytes); +} // namespace avx2 + +#endif + +} // namespace bit_util +} // namespace util + +namespace compute { + +/// Modify an Expression with pre-order and post-order visitation. +/// `pre` will be invoked on each Expression. `pre` will visit Calls before their +/// arguments, `post_call` will visit Calls (and no other Expressions) after their +/// arguments. Visitors should return the Identical expression to indicate no change; this +/// will prevent unnecessary construction in the common case where a modification is not +/// possible/necessary/... +/// +/// If an argument was modified, `post_call` visits a reconstructed Call with the modified +/// arguments but also receives a pointer to the unmodified Expression as a second +/// argument. If no arguments were modified the unmodified Expression* will be nullptr. +template +Result ModifyExpression(Expression expr, const PreVisit& pre, + const PostVisitCall& post_call) { + ARROW_ASSIGN_OR_RAISE(expr, Result(pre(std::move(expr)))); + + auto call = expr.call(); + if (!call) return expr; + + bool at_least_one_modified = false; + std::vector modified_arguments; + + for (size_t i = 0; i < call->arguments.size(); ++i) { + ARROW_ASSIGN_OR_RAISE(auto modified_argument, + ModifyExpression(call->arguments[i], pre, post_call)); + + if (Expression::Identical(modified_argument, call->arguments[i])) { + continue; + } + + if (!at_least_one_modified) { + modified_arguments = call->arguments; + at_least_one_modified = true; + } + + modified_arguments[i] = std::move(modified_argument); + } + + if (at_least_one_modified) { + // reconstruct the call expression with the modified arguments + auto modified_call = *call; + modified_call.arguments = std::move(modified_arguments); + return post_call(Expression(std::move(modified_call)), &expr); + } + + return post_call(std::move(expr), NULLPTR); +} + +// Helper class to calculate the modified number of rows to process using SIMD. +// +// Some array elements at the end will be skipped in order to avoid buffer +// overrun, when doing memory loads and stores using larger word size than a +// single array element. +// +class TailSkipForSIMD { + public: + static int64_t FixBitAccess(int num_bytes_accessed_together, int64_t num_rows, + int bit_offset) { + int64_t num_bytes = bit_util::BytesForBits(num_rows + bit_offset); + int64_t num_bytes_safe = + std::max(static_cast(0LL), num_bytes - num_bytes_accessed_together + 1); + int64_t num_rows_safe = + std::max(static_cast(0LL), 8 * num_bytes_safe - bit_offset); + return std::min(num_rows_safe, num_rows); + } + static int64_t FixBinaryAccess(int num_bytes_accessed_together, int64_t num_rows, + int64_t length) { + int64_t num_rows_to_skip = bit_util::CeilDiv(length, num_bytes_accessed_together); + int64_t num_rows_safe = + std::max(static_cast(0LL), num_rows - num_rows_to_skip); + return num_rows_safe; + } + static int64_t FixVarBinaryAccess(int num_bytes_accessed_together, int64_t num_rows, + const uint32_t* offsets) { + // Do not process rows that could read past the end of the buffer using N + // byte loads/stores. + // + int64_t num_rows_safe = num_rows; + while (num_rows_safe > 0 && + offsets[num_rows_safe] + num_bytes_accessed_together > offsets[num_rows]) { + --num_rows_safe; + } + return num_rows_safe; + } + static int FixSelection(int64_t num_rows_safe, int num_selected, + const uint16_t* selection) { + int num_selected_safe = num_selected; + while (num_selected_safe > 0 && selection[num_selected_safe - 1] >= num_rows_safe) { + --num_selected_safe; + } + return num_selected_safe; + } +}; + +} // namespace compute +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/visibility.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/visibility.h new file mode 100644 index 0000000000000000000000000000000000000000..ae994bd233329ff9ab0456191d3f8adf85ee3068 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/visibility.h @@ -0,0 +1,49 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) +# if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +# else +# pragma GCC diagnostic ignored "-Wattributes" +# endif + +# ifdef ARROW_COMPUTE_STATIC +# define ARROW_COMPUTE_EXPORT +# elif defined(ARROW_COMPUTE_EXPORTING) +# define ARROW_COMPUTE_EXPORT __declspec(dllexport) +# else +# define ARROW_COMPUTE_EXPORT __declspec(dllimport) +# endif + +# define ARROW_COMPUTE_NO_EXPORT + +# if defined(_MSC_VER) +# pragma warning(pop) +# endif + +#else // Not Windows +# ifndef ARROW_COMPUTE_EXPORT +# define ARROW_COMPUTE_EXPORT __attribute__((visibility("default"))) +# endif +# ifndef ARROW_COMPUTE_NO_EXPORT +# define ARROW_COMPUTE_NO_EXPORT __attribute__((visibility("hidden"))) +# endif +#endif diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/config.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/config.h new file mode 100644 index 0000000000000000000000000000000000000000..617d6c268b55ea344a3fe7f96141ff0f7e4d3f88 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/config.h @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/status.h" +#include "arrow/util/config.h" // IWYU pragma: export +#include "arrow/util/visibility.h" + +namespace arrow { + +struct BuildInfo { + /// The packed version number, e.g. 1002003 (decimal) for Arrow 1.2.3 + int version; + /// The "major" version number, e.g. 1 for Arrow 1.2.3 + int version_major; + /// The "minor" version number, e.g. 2 for Arrow 1.2.3 + int version_minor; + /// The "patch" version number, e.g. 3 for Arrow 1.2.3 + int version_patch; + /// The version string, e.g. "1.2.3" + std::string version_string; + std::string so_version; + std::string full_so_version; + + /// The CMake compiler identifier, e.g. "GNU" + std::string compiler_id; + std::string compiler_version; + std::string compiler_flags; + + /// The git changeset id, if available + std::string git_id; + /// The git changeset description, if available + std::string git_description; + std::string package_kind; + + /// The uppercase build type, e.g. "DEBUG" or "RELEASE" + std::string build_type; +}; + +struct RuntimeInfo { + /// The enabled SIMD level + /// + /// This can be less than `detected_simd_level` if the ARROW_USER_SIMD_LEVEL + /// environment variable is set to another value. + std::string simd_level; + + /// The SIMD level available on the OS and CPU + std::string detected_simd_level; + + /// Whether using the OS-based timezone database + /// This is set at compile-time. + bool using_os_timezone_db; + + /// The path to the timezone database; by default None. + std::optional timezone_db_path; +}; + +/// \brief Get runtime build info. +/// +/// The returned values correspond to exact loaded version of the Arrow library, +/// rather than the values frozen at application compile-time through the `ARROW_*` +/// preprocessor definitions. +ARROW_EXPORT +const BuildInfo& GetBuildInfo(); + +/// \brief Get runtime info. +/// +ARROW_EXPORT +RuntimeInfo GetRuntimeInfo(); + +struct GlobalOptions { + /// Path to text timezone database. This is only configurable on Windows, + /// which does not have a compatible OS timezone database. + std::optional timezone_db_path; +}; + +ARROW_EXPORT +Status Initialize(const GlobalOptions& options) noexcept; + +} // namespace arrow diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/datum.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/datum.h new file mode 100644 index 0000000000000000000000000000000000000000..4a88e7a81125cbed89d78d0e67288075ed9295f8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/datum.h @@ -0,0 +1,314 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/array/data.h" +#include "arrow/device_allocation_type_set.h" +#include "arrow/scalar.h" +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class Array; +class ChunkedArray; +class RecordBatch; +class Table; + +/// \class Datum +/// \brief Variant type for various Arrow C++ data structures +struct ARROW_EXPORT Datum { + /// \brief The kind of datum stored + enum Kind { NONE, SCALAR, ARRAY, CHUNKED_ARRAY, RECORD_BATCH, TABLE }; + + /// \brief A placeholder type to represent empty datum + struct Empty {}; + + /// \brief Datums variants may have a length. This special value indicate that the + /// current variant does not have a length. + static constexpr int64_t kUnknownLength = -1; + + /// \brief Storage of the actual datum. + /// + /// Note: For arrays, ArrayData is stored instead of Array for easier processing + std::variant, std::shared_ptr, + std::shared_ptr, std::shared_ptr, + std::shared_ptr
> + value; + + /// \brief Empty datum, to be populated elsewhere + Datum() = default; + + Datum(const Datum& other) = default; + Datum& operator=(const Datum& other) = default; + Datum(Datum&& other) = default; + Datum& operator=(Datum&& other) = default; + + /// \brief Construct from a Scalar + Datum(std::shared_ptr value) // NOLINT implicit conversion + : value(std::move(value)) {} + + /// \brief Construct from an ArrayData + Datum(std::shared_ptr value) // NOLINT implicit conversion + : value(std::move(value)) {} + + /// \brief Construct from an ArrayData + Datum(ArrayData arg) // NOLINT implicit conversion + : value(std::make_shared(std::move(arg))) {} + + /// \brief Construct from an Array + Datum(const Array& value); // NOLINT implicit conversion + + /// \brief Construct from an Array + Datum(const std::shared_ptr& value); // NOLINT implicit conversion + + /// \brief Construct from a ChunkedArray + Datum(std::shared_ptr value); // NOLINT implicit conversion + + /// \brief Construct from a RecordBatch + Datum(std::shared_ptr value); // NOLINT implicit conversion + + /// \brief Construct from a Table + Datum(std::shared_ptr
value); // NOLINT implicit conversion + + /// \brief Construct from a ChunkedArray. + /// + /// This can be expensive, prefer the shared_ptr constructor + explicit Datum(const ChunkedArray& value); + + /// \brief Construct from a RecordBatch. + /// + /// This can be expensive, prefer the shared_ptr constructor + explicit Datum(const RecordBatch& value); + + /// \brief Construct from a Table. + /// + /// This can be expensive, prefer the shared_ptr
constructor + explicit Datum(const Table& value); + + /// \brief Cast from concrete subtypes of Array or Scalar to Datum + template , + bool IsScalar = std::is_base_of_v, + typename = enable_if_t> + Datum(std::shared_ptr value) // NOLINT implicit conversion + : Datum(std::shared_ptr::type>( + std::move(value))) {} + + /// \brief Cast from concrete subtypes of Array or Scalar to Datum + template , + bool IsArray = std::is_base_of_v, + bool IsScalar = std::is_base_of_v, + typename = enable_if_t> + Datum(T&& value) // NOLINT implicit conversion + : Datum(std::make_shared(std::forward(value))) {} + + /// \brief Copy from concrete subtypes of Scalar. + /// + /// The concrete scalar type must be copyable (not all of them are). + template >> + Datum(const T& value) // NOLINT implicit conversion + : Datum(std::make_shared(value)) {} + + // Convenience constructors + /// \brief Convenience constructor storing a bool scalar. + explicit Datum(bool value); + /// \brief Convenience constructor storing an int8 scalar. + explicit Datum(int8_t value); + /// \brief Convenience constructor storing a uint8 scalar. + explicit Datum(uint8_t value); + /// \brief Convenience constructor storing an int16 scalar. + explicit Datum(int16_t value); + /// \brief Convenience constructor storing a uint16 scalar. + explicit Datum(uint16_t value); + /// \brief Convenience constructor storing an int32 scalar. + explicit Datum(int32_t value); + /// \brief Convenience constructor storing a uint32 scalar. + explicit Datum(uint32_t value); + /// \brief Convenience constructor storing an int64 scalar. + explicit Datum(int64_t value); + /// \brief Convenience constructor storing a uint64 scalar. + explicit Datum(uint64_t value); + /// \brief Convenience constructor storing a float scalar. + explicit Datum(float value); + /// \brief Convenience constructor storing a double scalar. + explicit Datum(double value); + /// \brief Convenience constructor storing a string scalar. + explicit Datum(std::string value); + /// \brief Convenience constructor storing a string scalar. + explicit Datum(const char* value); + + /// \brief Convenience constructor for a DurationScalar from std::chrono::duration + template