Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/_multiprocess/__init__.py +8 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/INSTALLER +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/METADATA +499 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/RECORD +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/WHEEL +5 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/direct_url.json +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/top_level.txt +3 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/INSTALLER +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/METADATA +450 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/RECORD +297 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/WHEEL +5 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/top_level.txt +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/INSTALLER +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/METADATA +295 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/RECORD +10 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/WHEEL +4 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/__init__.py +432 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/py.typed +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/test_cases.py +151 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/INSTALLER +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/METADATA +10 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/RECORD +123 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/WHEEL +5 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/entry_points.txt +2 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/top_level.txt +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/Dockerfile +27 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/README.md +65 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/__init__.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/app.py +85 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/execution.py +521 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/__init__.py +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/bettermap.py +215 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/__init__.py +14 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_errors.h +149 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_include.h +389 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_embedding.h +550 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_imp_emulation.py +83 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_shimmed_dist_utils.py +45 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/api.py +967 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/backend_ctypes.py +1121 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cffi_opcode.py +187 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/commontypes.py +82 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cparser.py +1015 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/error.py +31 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/ffiplatform.py +113 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/lock.py +30 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/model.py +618 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/parse_c_type.h +181 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/pkgconfig.py +121 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/recompiler.py +1598 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/_multiprocess/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
|
| 4 |
+
# Copyright (c) 2022-2024 The Uncertainty Quantification Foundation.
|
| 5 |
+
# License: 3-clause BSD. The full license text is available at:
|
| 6 |
+
# - https://github.com/uqfoundation/multiprocess/blob/master/LICENSE
|
| 7 |
+
|
| 8 |
+
from _multiprocessing import *
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_ol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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: ai2-olmo
|
| 3 |
+
Version: 0.6.0
|
| 4 |
+
Summary: Open Language Model (OLMo)
|
| 5 |
+
Author-email: Allen Institute for Artificial Intelligence <olmo@allenai.org>
|
| 6 |
+
License: Apache License
|
| 7 |
+
Version 2.0, January 2004
|
| 8 |
+
https://www.apache.org/licenses/
|
| 9 |
+
|
| 10 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 11 |
+
|
| 12 |
+
1. Definitions.
|
| 13 |
+
|
| 14 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 15 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 16 |
+
|
| 17 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 18 |
+
the copyright owner that is granting the License.
|
| 19 |
+
|
| 20 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 21 |
+
other entities that control, are controlled by, or are under common
|
| 22 |
+
control with that entity. For the purposes of this definition,
|
| 23 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 24 |
+
direction or management of such entity, whether by contract or
|
| 25 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 26 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 27 |
+
|
| 28 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 29 |
+
exercising permissions granted by this License.
|
| 30 |
+
|
| 31 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 32 |
+
including but not limited to software source code, documentation
|
| 33 |
+
source, and configuration files.
|
| 34 |
+
|
| 35 |
+
"Object" form shall mean any form resulting from mechanical
|
| 36 |
+
transformation or translation of a Source form, including but
|
| 37 |
+
not limited to compiled object code, generated documentation,
|
| 38 |
+
and conversions to other media types.
|
| 39 |
+
|
| 40 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 41 |
+
Object form, made available under the License, as indicated by a
|
| 42 |
+
copyright notice that is included in or attached to the work
|
| 43 |
+
(an example is provided in the Appendix below).
|
| 44 |
+
|
| 45 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 46 |
+
form, that is based on (or derived from) the Work and for which the
|
| 47 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 48 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 49 |
+
of this License, Derivative Works shall not include works that remain
|
| 50 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 51 |
+
the Work and Derivative Works thereof.
|
| 52 |
+
|
| 53 |
+
"Contribution" shall mean any work of authorship, including
|
| 54 |
+
the original version of the Work and any modifications or additions
|
| 55 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 56 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 57 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 58 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 59 |
+
means any form of electronic, verbal, or written communication sent
|
| 60 |
+
to the Licensor or its representatives, including but not limited to
|
| 61 |
+
communication on electronic mailing lists, source code control systems,
|
| 62 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 63 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 64 |
+
excluding communication that is conspicuously marked or otherwise
|
| 65 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 66 |
+
|
| 67 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 68 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 69 |
+
subsequently incorporated within the Work.
|
| 70 |
+
|
| 71 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 72 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 73 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 74 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 75 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 76 |
+
Work and such Derivative Works in Source or Object form.
|
| 77 |
+
|
| 78 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 79 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 80 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 81 |
+
(except as stated in this section) patent license to make, have made,
|
| 82 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 83 |
+
where such license applies only to those patent claims licensable
|
| 84 |
+
by such Contributor that are necessarily infringed by their
|
| 85 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 86 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 87 |
+
institute patent litigation against any entity (including a
|
| 88 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 89 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 90 |
+
or contributory patent infringement, then any patent licenses
|
| 91 |
+
granted to You under this License for that Work shall terminate
|
| 92 |
+
as of the date such litigation is filed.
|
| 93 |
+
|
| 94 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 95 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 96 |
+
modifications, and in Source or Object form, provided that You
|
| 97 |
+
meet the following conditions:
|
| 98 |
+
|
| 99 |
+
(a) You must give any other recipients of the Work or
|
| 100 |
+
Derivative Works a copy of this License; and
|
| 101 |
+
|
| 102 |
+
(b) You must cause any modified files to carry prominent notices
|
| 103 |
+
stating that You changed the files; and
|
| 104 |
+
|
| 105 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 106 |
+
that You distribute, all copyright, patent, trademark, and
|
| 107 |
+
attribution notices from the Source form of the Work,
|
| 108 |
+
excluding those notices that do not pertain to any part of
|
| 109 |
+
the Derivative Works; and
|
| 110 |
+
|
| 111 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 112 |
+
distribution, then any Derivative Works that You distribute must
|
| 113 |
+
include a readable copy of the attribution notices contained
|
| 114 |
+
within such NOTICE file, excluding those notices that do not
|
| 115 |
+
pertain to any part of the Derivative Works, in at least one
|
| 116 |
+
of the following places: within a NOTICE text file distributed
|
| 117 |
+
as part of the Derivative Works; within the Source form or
|
| 118 |
+
documentation, if provided along with the Derivative Works; or,
|
| 119 |
+
within a display generated by the Derivative Works, if and
|
| 120 |
+
wherever such third-party notices normally appear. The contents
|
| 121 |
+
of the NOTICE file are for informational purposes only and
|
| 122 |
+
do not modify the License. You may add Your own attribution
|
| 123 |
+
notices within Derivative Works that You distribute, alongside
|
| 124 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 125 |
+
that such additional attribution notices cannot be construed
|
| 126 |
+
as modifying the License.
|
| 127 |
+
|
| 128 |
+
You may add Your own copyright statement to Your modifications and
|
| 129 |
+
may provide additional or different license terms and conditions
|
| 130 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 131 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 132 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 133 |
+
the conditions stated in this License.
|
| 134 |
+
|
| 135 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 136 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 137 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 138 |
+
this License, without any additional terms or conditions.
|
| 139 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 140 |
+
the terms of any separate license agreement you may have executed
|
| 141 |
+
with Licensor regarding such Contributions.
|
| 142 |
+
|
| 143 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 144 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 145 |
+
except as required for reasonable and customary use in describing the
|
| 146 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 147 |
+
|
| 148 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 149 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 150 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 151 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 152 |
+
implied, including, without limitation, any warranties or conditions
|
| 153 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 154 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 155 |
+
appropriateness of using or redistributing the Work and assume any
|
| 156 |
+
risks associated with Your exercise of permissions under this License.
|
| 157 |
+
|
| 158 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 159 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 160 |
+
unless required by applicable law (such as deliberate and grossly
|
| 161 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 162 |
+
liable to You for damages, including any direct, indirect, special,
|
| 163 |
+
incidental, or consequential damages of any character arising as a
|
| 164 |
+
result of this License or out of the use or inability to use the
|
| 165 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 166 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 167 |
+
other commercial damages or losses), even if such Contributor
|
| 168 |
+
has been advised of the possibility of such damages.
|
| 169 |
+
|
| 170 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 171 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 172 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 173 |
+
or other liability obligations and/or rights consistent with this
|
| 174 |
+
License. However, in accepting such obligations, You may act only
|
| 175 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 176 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 177 |
+
defend, and hold each Contributor harmless for any liability
|
| 178 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 179 |
+
of your accepting any such warranty or additional liability.
|
| 180 |
+
|
| 181 |
+
END OF TERMS AND CONDITIONS
|
| 182 |
+
|
| 183 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 184 |
+
|
| 185 |
+
To apply the Apache License to your work, attach the following
|
| 186 |
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
| 187 |
+
replaced with your own identifying information. (Don't include
|
| 188 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 189 |
+
comment syntax for the file format. We also recommend that a
|
| 190 |
+
file or class name and description of purpose be included on the
|
| 191 |
+
same "printed page" as the copyright notice for easier
|
| 192 |
+
identification within third-party archives.
|
| 193 |
+
|
| 194 |
+
Copyright {yyyy} {name of copyright owner}
|
| 195 |
+
|
| 196 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 197 |
+
you may not use this file except in compliance with the License.
|
| 198 |
+
You may obtain a copy of the License at
|
| 199 |
+
|
| 200 |
+
https://www.apache.org/licenses/LICENSE-2.0
|
| 201 |
+
|
| 202 |
+
Unless required by applicable law or agreed to in writing, software
|
| 203 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 204 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 205 |
+
See the License for the specific language governing permissions and
|
| 206 |
+
limitations under the License.
|
| 207 |
+
|
| 208 |
+
Project-URL: Homepage, https://github.com/allenai/OLMo
|
| 209 |
+
Project-URL: Repository, https://github.com/allenai/OLMo
|
| 210 |
+
Requires-Python: >=3.10
|
| 211 |
+
Description-Content-Type: text/markdown
|
| 212 |
+
License-File: LICENSE
|
| 213 |
+
Requires-Dist: numpy<2
|
| 214 |
+
Requires-Dist: torch>=2.1
|
| 215 |
+
Requires-Dist: ai2-olmo-core>=1.8.0
|
| 216 |
+
Requires-Dist: omegaconf
|
| 217 |
+
Requires-Dist: rich
|
| 218 |
+
Requires-Dist: boto3
|
| 219 |
+
Requires-Dist: google-cloud-storage
|
| 220 |
+
Requires-Dist: tokenizers
|
| 221 |
+
Requires-Dist: packaging
|
| 222 |
+
Requires-Dist: cached_path>=1.6.2
|
| 223 |
+
Requires-Dist: transformers
|
| 224 |
+
Requires-Dist: importlib_resources
|
| 225 |
+
Provides-Extra: dev
|
| 226 |
+
Requires-Dist: ruff; extra == "dev"
|
| 227 |
+
Requires-Dist: mypy<1.4,>=1.0; extra == "dev"
|
| 228 |
+
Requires-Dist: black<24.0,>=23.1; extra == "dev"
|
| 229 |
+
Requires-Dist: isort<5.13,>=5.12; extra == "dev"
|
| 230 |
+
Requires-Dist: pytest; extra == "dev"
|
| 231 |
+
Requires-Dist: pytest-sphinx; extra == "dev"
|
| 232 |
+
Requires-Dist: twine>=1.11.0; extra == "dev"
|
| 233 |
+
Requires-Dist: setuptools; extra == "dev"
|
| 234 |
+
Requires-Dist: wheel; extra == "dev"
|
| 235 |
+
Requires-Dist: build; extra == "dev"
|
| 236 |
+
Provides-Extra: train
|
| 237 |
+
Requires-Dist: wandb; extra == "train"
|
| 238 |
+
Requires-Dist: beaker-gantry; extra == "train"
|
| 239 |
+
Requires-Dist: click; extra == "train"
|
| 240 |
+
Requires-Dist: torchmetrics; extra == "train"
|
| 241 |
+
Requires-Dist: smashed[remote]>=0.21.1; extra == "train"
|
| 242 |
+
Requires-Dist: safetensors; extra == "train"
|
| 243 |
+
Requires-Dist: datasets; extra == "train"
|
| 244 |
+
Requires-Dist: scikit-learn; extra == "train"
|
| 245 |
+
Requires-Dist: msgspec>=0.14.0; extra == "train"
|
| 246 |
+
Provides-Extra: all
|
| 247 |
+
Requires-Dist: ai2-olmo[dev,train]; extra == "all"
|
| 248 |
+
Provides-Extra: figures
|
| 249 |
+
Requires-Dist: matplotlib; extra == "figures"
|
| 250 |
+
Dynamic: license-file
|
| 251 |
+
|
| 252 |
+
<div align="center">
|
| 253 |
+
<!-- <img src="https://github.com/allenai/OLMo/assets/8812459/774ac485-a535-4768-8f7c-db7be20f5cc3" width="300"/> -->
|
| 254 |
+
<br>
|
| 255 |
+
<br>
|
| 256 |
+
<h1>OLMo: Open Language Model</h1>
|
| 257 |
+
</div>
|
| 258 |
+
<p align="center">
|
| 259 |
+
<a href="https://github.com/allenai/OLMo/blob/main/LICENSE">
|
| 260 |
+
<img alt="GitHub License" src="https://img.shields.io/github/license/allenai/OLMo">
|
| 261 |
+
</a>
|
| 262 |
+
<a href="https://github.com/allenai/OLMo/releases">
|
| 263 |
+
<img alt="GitHub release" src="https://img.shields.io/github/release/allenai/OLMo.svg">
|
| 264 |
+
</a>
|
| 265 |
+
<a href="https://arxiv.org/pdf/2501.00656.pdf">
|
| 266 |
+
<img alt="Paper URL" src="https://img.shields.io/badge/arxiv-2402.00838-blue">
|
| 267 |
+
</a>
|
| 268 |
+
<a href="https://playground.allenai.org">
|
| 269 |
+
<img alt="Playground" src="https://img.shields.io/badge/Ai2-Playground-F0529C">
|
| 270 |
+
</a>
|
| 271 |
+
<a href="https://discord.gg/sZq3jTNVNG">
|
| 272 |
+
<img alt="Discord" src="https://img.shields.io/badge/Discord%20-%20blue?style=flat&logo=discord&label=Ai2&color=%235B65E9">
|
| 273 |
+
</a>
|
| 274 |
+
</p>
|
| 275 |
+
|
| 276 |
+
# ⚠️ NOTICE ⚠️ This repository is out of date with our more recent releases and is no longer active. For the latest Olmo releases and updates, please visit: https://github.com/allenai/OLMo-core/
|
| 277 |
+
|
| 278 |
+
OLMo is a repository for training and using AI2's state-of-the-art open language models. It is designed by scientists, for scientists.
|
| 279 |
+
|
| 280 |
+
## Installation
|
| 281 |
+
|
| 282 |
+
First, install [PyTorch](https://pytorch.org) following the instructions specific to your operating system.
|
| 283 |
+
|
| 284 |
+
For training and fine-tuning, we recommend installing from source:
|
| 285 |
+
|
| 286 |
+
```bash
|
| 287 |
+
git clone https://github.com/allenai/OLMo.git
|
| 288 |
+
cd OLMo
|
| 289 |
+
pip install -e .[all]
|
| 290 |
+
```
|
| 291 |
+
You can also install from PyPI with:
|
| 292 |
+
```bash
|
| 293 |
+
pip install ai2-olmo
|
| 294 |
+
```
|
| 295 |
+
|
| 296 |
+
## Pretraining
|
| 297 |
+
|
| 298 |
+
OLMo pretraining follows a two-stage training procedure.
|
| 299 |
+
In the first stage, we train on large amounts of mostly web-based data: [OLMo-mix-1124](https://huggingface.co/datasets/allenai/olmo-mix-1124)
|
| 300 |
+
In the second stage, we train on a smaller amount of high-quality, targeted data: [Dolmino-mix-1124](https://huggingface.co/datasets/allenai/dolmino-mix-1124)
|
| 301 |
+
|
| 302 |
+
You can find *all* the checkpoints, at minimum every 1000 training steps in OLMo core and Hugging Face format:
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
| Variant | OLMo Format (Stage 1) | OLMo Format (Stage 2) | Hugging Face Format |
|
| 306 |
+
|----------------|-----------------------------------------------------------------------------------------------------|--------|----------------------------------------------------------------------------------|
|
| 307 |
+
| **OLMo-2 1B** | [OLMo-2 1B](https://github.com/allenai/OLMo/blob/main/configs/official-0425/OLMo-2-0425-1B.csv) | [OLMo-2 1B](https://github.com/allenai/OLMo/blob/main/configs/official-0425/OLMo-2-0425-1B-stage2.csv) | [Hugging Face for the 1B variant](https://huggingface.co/allenai/OLMo-2-0425-1B) |
|
| 308 |
+
| **OLMo-2 7B** | [OLMo-2 7B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-7B.csv) | [OLMo-2 7B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-7B-stage2.csv) | [Hugging Face for the 7B variant](https://huggingface.co/allenai/OLMo-2-1124-7B) |
|
| 309 |
+
| **OLMo-2 13B** | [OLMo-2 13B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-13B.csv) | [OLMo-2 13B](https://github.com/allenai/OLMo/blob/main/configs/official-1124/OLMo-2-1124-13B-stage2.csv) | [Hugging Face for the 13B variant](https://huggingface.co/allenai/OLMo-2-1124-13B) |
|
| 310 |
+
| **OLMo-2 32B** | [OLMo-2 32B](https://github.com/allenai/OLMo-core/blob/main/src/scripts/official/OLMo2-0325-32B.csv) | [OLMo-2 32B](https://github.com/allenai/OLMo-core/blob/main/src/scripts/official/OLMo-2-0325-32B-stage2.csv) | [Hugging Face for the 32B variant](https://huggingface.co/allenai/OLMo-2-0325-32B) |
|
| 311 |
+
|
| 312 |
+
> Note: The 32B variant was trained on our new trainer. To train or fine-tune OLMo-2 32B, visit [OLMo-core](https://github.com/allenai/OLMo-core).
|
| 313 |
+
|
| 314 |
+
### Steps to reproduce
|
| 315 |
+
|
| 316 |
+
To reproduce any of the training processes described below, run this:
|
| 317 |
+
|
| 318 |
+
```bash
|
| 319 |
+
torchrun --nproc_per_node=8 scripts/train.py {path_to_train_config}
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
For the training config, use any of the configs listed below.
|
| 323 |
+
|
| 324 |
+
If you want to override any of the settings in the training config without having to write a new config every time,
|
| 325 |
+
you can do this:
|
| 326 |
+
|
| 327 |
+
```bash
|
| 328 |
+
torchrun --nproc_per_node=8 scripts/train.py {path_to_train_config} \
|
| 329 |
+
--setting1=value \
|
| 330 |
+
--setting2=value \
|
| 331 |
+
--setting3.subsetting1=value
|
| 332 |
+
```
|
| 333 |
+
|
| 334 |
+
The training configs below refer to training data that gets streamed in live over HTTP.
|
| 335 |
+
To reproduce at large scale, we recommend downloading the files locally and changing the paths to point to your
|
| 336 |
+
local file system.
|
| 337 |
+
|
| 338 |
+
#### To run on Mac silicon devices:
|
| 339 |
+
```bash
|
| 340 |
+
python scripts/train.py {path_to_train_config}
|
| 341 |
+
```
|
| 342 |
+
Example:
|
| 343 |
+
```bash
|
| 344 |
+
python scripts/train.py configs/tiny/OLMo-20M.yaml --save_overwrite
|
| 345 |
+
```
|
| 346 |
+
> Note: You need to upgrade PyTorch to 2.5.x to run.
|
| 347 |
+
|
| 348 |
+
### Stage 1
|
| 349 |
+
|
| 350 |
+
Stage 1 is the biggest stage, where we train on 4T or 5T tokens on largely web-based data.
|
| 351 |
+
|
| 352 |
+
| | OLMo2 1B | OLMo2 7B | OLMo2 13B |
|
| 353 |
+
|-----------------|-----------------|-------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|
|
| 354 |
+
| Number of tokens| 4 Trillion | 4 Trillion | 5 Trillion |
|
| 355 |
+
| Checkpoint |[stage1-step1907359-tokens4001B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage1-step1907359-tokens4001B)| [stage1-step928646-tokens3896B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage1-step928646-tokens3896B) | [stage1-step596057-tokens5001B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage1-step596057-tokens5001B) |
|
| 356 |
+
| Training config | [OLMo2-1B-stage1.yaml](configs/official-0425/OLMo2-1B-stage1.yaml) |[OLMo2-7B-stage1.yaml](configs/official-1124/OLMo2-7B-stage1.yaml) | [OLMo2-13B-stage1.yaml](configs/official-1124/OLMo2-13B-stage1.yaml) | |
|
| 357 |
+
| WandB | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0)|[wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/OLMo-2-7B-Nov-2024--VmlldzoxMDUzMzE1OA) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) |
|
| 358 |
+
|
| 359 |
+
You can find the .csv.gz files containing the training data [here](configs/official-1124/provenance.csv).
|
| 360 |
+
|
| 361 |
+
### Stage 2 for the 1B
|
| 362 |
+
|
| 363 |
+
For the 1B model, we have trained three times with different data order on 50B high quality tokens, used last checkpoint of seed 42 as final checkpoint.
|
| 364 |
+
|
| 365 |
+
| | Checkpoint | Training config | WandB |
|
| 366 |
+
|------------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|-------------|
|
| 367 |
+
| random seed 42069 | [stage2-ingredient1-step23852-tokens51B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage2-ingredient1-step23852-tokens51B) | [OLMo2-1B-stage2-seed42069.yaml](configs/official-0425/OLMo2-1B-stage2-seed42069.yaml) | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0) |
|
| 368 |
+
| random seed 666 | [stage2-ingredient2-step23852-tokens51B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage2-ingredient2-step23852-tokens51B) | [OLMo2-1B-stage2-seed666.yaml](configs/official-0425/OLMo2-1B-stage2-seed666.yaml) | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0) |
|
| 369 |
+
| random seed 42 (main) | [stage2-ingredient3-step23852-tokens51B](https://huggingface.co/allenai/OLMo-2-0425-1B/tree/stage2-ingredient3-step23852-tokens51B) | [OLMo2-1B-stage2-seed42.yaml](configs/official-0425/OLMo2-1B-stage2-seed42.yaml) | [wandb.ai/OLMo2-1B](https://api.wandb.ai/links/ai2-llm/izdtrtu0) |
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
### Stage 2 for the 7B
|
| 373 |
+
|
| 374 |
+
For the 7B model, we train three times with different data order on 50B high quality tokens, and then average ("soup") the models.
|
| 375 |
+
|
| 376 |
+
| | Checkpoint | Training config | WandB |
|
| 377 |
+
|------------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|-------------|
|
| 378 |
+
| random seed 42 | [stage2-ingredient1-step11931-tokens50B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage2-ingredient1-step11931-tokens50B) | [OLMo2-7B-stage2-seed42.yaml](configs/official-1124/OLMo2-7B-stage2-seed42.yaml) | [wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/) |
|
| 379 |
+
| random seed 42069 | [stage2-ingredient2-step11931-tokens50B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage2-ingredient2-step11931-tokens50B) | [OLMo2-7B-stage2-seed42069.yaml](configs/official-1124/OLMo2-7B-stage2-seed42069.yaml) | [wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/) |
|
| 380 |
+
| random seed 666 | [stage2-ingredient3-step11931-tokens50B](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/stage2-ingredient3-step11931-tokens50B) | [OLMo2-7B-stage2-seed666.yaml](configs/official-1124/OLMo2-7B-stage2-seed666.yaml) | [wandb.ai/OLMo2-7B](https://wandb.ai/ai2-llm/OLMo-2-1124-7B/reports/) |
|
| 381 |
+
| **final souped model** | [main](https://huggingface.co/allenai/OLMo-2-1124-7B/tree/main) | no config, we just averaged the weights in Python | |
|
| 382 |
+
|
| 383 |
+
The training configs linked here are set up to download the latest checkpoint after stage 1, and start training from there.
|
| 384 |
+
|
| 385 |
+
### Stage 2 for the 13B
|
| 386 |
+
|
| 387 |
+
For the 13B model, we train three times with different data order on 100B high quality tokens, and one more time
|
| 388 |
+
on 300B high quality tokens. Then we average ("soup") the models.
|
| 389 |
+
|
| 390 |
+
| | Checkpoint | Training config | WandB |
|
| 391 |
+
|------------------------|----------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|-------------|
|
| 392 |
+
| random seed 1110, 100B | [stage2-ingredient1-step11931-tokens100B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient1-step11931-tokens100B) | [OLMo2-13B-stage2-seed1110-100B.yaml](configs/official-1124/OLMo2-13B-stage2-seed1110-100B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) |
|
| 393 |
+
| random seed 2662, 100B | [stage2-ingredient2-step11931-tokens100B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient2-step11931-tokens100B) | [OLMo2-13B-stage2-seed2662-100B.yaml](configs/official-1124/OLMo2-13B-stage2-seed2662-100B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) |
|
| 394 |
+
| random seed 6209, 100B | [stage2-ingredient3-step11931-tokens100B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient3-step11931-tokens100B) | [OLMo2-13B-stage2-seed6209-100B.yaml](configs/official-1124/OLMo2-13B-stage2-seed6209-100B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) |
|
| 395 |
+
| random seed 2662, 300B | [stage2-ingredient4-step11931-tokens300B](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/stage2-ingredient4-step35773-tokens300B) | [OLMo2-13B-stage2-seed2662-300B.yaml](configs/official-1124/OLMo2-13B-stage2-seed2662-300B.yaml) | [wandb.ai/OLMo2-13B](https://wandb.ai/ai2-llm/OLMo-2-1124-13B/reports/OLMo-2-13B-Nov-2024--VmlldzoxMDUzMjQxNg) |
|
| 396 |
+
| **final souped model** | [main](https://huggingface.co/allenai/OLMo-2-1124-13B/tree/main) | no config, we just averaged the weights in Python | |
|
| 397 |
+
|
| 398 |
+
The training configs linked here are set up to download the latest checkpoints after stage 1, and start training from there.
|
| 399 |
+
|
| 400 |
+
> Note: You can find all the information about the 32B in the [OLMo-core](https://github.com/allenai/OLMo-core) repository.
|
| 401 |
+
|
| 402 |
+
## Instruction tuned variants
|
| 403 |
+
|
| 404 |
+
For instruction tuned variants of these models, go to
|
| 405 |
+
* [OLMo2 1B Instruct](https://huggingface.co/allenai/OLMo-2-0425-1B-Instruct)
|
| 406 |
+
* [OLMo2 7B Instruct](https://huggingface.co/allenai/OLMo-2-1124-7B-Instruct)
|
| 407 |
+
* [OLMo2 13B Instruct](https://huggingface.co/allenai/OLMo-2-1124-13B-Instruct)
|
| 408 |
+
* [OLMo2 32B Instruct](https://huggingface.co/allenai/OLMo-2-0325-32B-Instruct)
|
| 409 |
+
|
| 410 |
+
## Inference
|
| 411 |
+
|
| 412 |
+
You can use our Hugging Face integration to run inference on the OLMo Transformers checkpoints:
|
| 413 |
+
|
| 414 |
+
```python
|
| 415 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 416 |
+
olmo = AutoModelForCausalLM.from_pretrained("allenai/OLMo-2-0425-1B")
|
| 417 |
+
tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-2-0425-1B")
|
| 418 |
+
message = ["Language modeling is "]
|
| 419 |
+
inputs = tokenizer(message, return_tensors='pt', return_token_type_ids=False)
|
| 420 |
+
# optional verifying cuda
|
| 421 |
+
# inputs = {k: v.to('cuda') for k,v in inputs.items()}
|
| 422 |
+
# olmo = olmo.to('cuda')
|
| 423 |
+
response = olmo.generate(**inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)
|
| 424 |
+
print(tokenizer.batch_decode(response, skip_special_tokens=True)[0])
|
| 425 |
+
```
|
| 426 |
+
|
| 427 |
+
Alternatively, with the Hugging Face pipeline abstraction:
|
| 428 |
+
|
| 429 |
+
```python
|
| 430 |
+
from transformers import pipeline
|
| 431 |
+
olmo_pipe = pipeline("text-generation", model="allenai/OLMo-2-0425-1B")
|
| 432 |
+
print(olmo_pipe("Language modeling is"))
|
| 433 |
+
```
|
| 434 |
+
|
| 435 |
+
### Quantization
|
| 436 |
+
|
| 437 |
+
```python
|
| 438 |
+
olmo = AutoModelForCausalLM.from_pretrained("allenai/OLMo-2-0425-1B", torch_dtype=torch.float16, load_in_8bit=True) # requires bitsandbytes
|
| 439 |
+
```
|
| 440 |
+
|
| 441 |
+
The quantized model is sensitive to input types and CUDA handling. To avoid potential issues, we recommend explicitly converting input IDs to CUDA using: `inputs.input_ids.to('cuda')`
|
| 442 |
+
|
| 443 |
+
## Evaluation
|
| 444 |
+
|
| 445 |
+
Additional tools for evaluating OLMo models are available at the [OLMo Eval](https://github.com/allenai/OLMo-eval) and [olmes](https://github.com/allenai/olmes) repositories.
|
| 446 |
+
|
| 447 |
+
## Modal.com Hosting
|
| 448 |
+
|
| 449 |
+
An example script is provided for hosting an OLMo 2 model on Modal.com using the OpenAI API in `./scripts/olmo2_modal_openai.py`.
|
| 450 |
+
To run that:
|
| 451 |
+
|
| 452 |
+
1. Follow the instructions under Getting Started in [the Modal.com Guide](https://modal.com/docs/guide) to install
|
| 453 |
+
the Modal library and command line tools.</li>
|
| 454 |
+
2. Follow the instructions under [Secrets](https://modal.com/docs/guide/secrets) in the Modal.com Guide to create a Modal secret named "example-secret-token"
|
| 455 |
+
that defines a value for the variable MODAL_TOKEN for your server.</li>
|
| 456 |
+
3. Then run
|
| 457 |
+
```bash
|
| 458 |
+
modal deploy ./scripts/olmo2_modal_openai.py
|
| 459 |
+
```
|
| 460 |
+
|
| 461 |
+
You can check your endpoint using curl similar to the following:
|
| 462 |
+
```bash
|
| 463 |
+
curl -X POST \
|
| 464 |
+
-H "Authorization: Bearer [the secret token from above]" \
|
| 465 |
+
-H "Content-Type: application/json" \
|
| 466 |
+
-d @body.json \
|
| 467 |
+
https://[the web endpoint modal creates above]/v1/chat/completions
|
| 468 |
+
```
|
| 469 |
+
|
| 470 |
+
where `body.json` is of the form:
|
| 471 |
+
```
|
| 472 |
+
{
|
| 473 |
+
"model": "OLMo-2-1124-13B-Instruct",
|
| 474 |
+
"messages": [
|
| 475 |
+
{
|
| 476 |
+
"role": "user",
|
| 477 |
+
"content": "Who was Alan Turing?"
|
| 478 |
+
}
|
| 479 |
+
],
|
| 480 |
+
"max_tokens": 100,
|
| 481 |
+
"temperature": 0.9,
|
| 482 |
+
"stream": true
|
| 483 |
+
}
|
| 484 |
+
```
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
## Citing
|
| 488 |
+
|
| 489 |
+
```bibtex
|
| 490 |
+
@misc{olmo20242olmo2furious,
|
| 491 |
+
title={2 OLMo 2 Furious},
|
| 492 |
+
author={Team OLMo and Pete Walsh and Luca Soldaini and Dirk Groeneveld and Kyle Lo and Shane Arora and Akshita Bhagia and Yuling Gu and Shengyi Huang and Matt Jordan and Nathan Lambert and Dustin Schwenk and Oyvind Tafjord and Taira Anderson and David Atkinson and Faeze Brahman and Christopher Clark and Pradeep Dasigi and Nouha Dziri and Michal Guerquin and Hamish Ivison and Pang Wei Koh and Jiacheng Liu and Saumya Malik and William Merrill and Lester James V. Miranda and Jacob Morrison and Tyler Murray and Crystal Nam and Valentina Pyatkin and Aman Rangapur and Michael Schmitz and Sam Skjonsberg and David Wadden and Christopher Wilhelm and Michael Wilson and Luke Zettlemoyer and Ali Farhadi and Noah A. Smith and Hannaneh Hajishirzi},
|
| 493 |
+
year={2024},
|
| 494 |
+
eprint={2501.00656},
|
| 495 |
+
archivePrefix={arXiv},
|
| 496 |
+
primaryClass={cs.CL},
|
| 497 |
+
url={https://arxiv.org/abs/2501.00656},
|
| 498 |
+
}
|
| 499 |
+
```
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (82.0.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"url": "https://github.com/allenai/OLMo.git", "vcs_info": {"commit_id": "090253dac6688f2532509daa7aa2eb5fae50e956", "requested_revision": "main", "vcs": "git"}}
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo-0.6.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
hf_olmo
|
| 2 |
+
olmo
|
| 3 |
+
olmo_data
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/METADATA
ADDED
|
@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: ai2-olmo-core
|
| 3 |
+
Version: 2.4.0
|
| 4 |
+
Summary: Core training module for the Open Language Model (OLMo)
|
| 5 |
+
Author-email: Allen Institute for Artificial Intelligence <olmo@allenai.org>
|
| 6 |
+
License: Apache License
|
| 7 |
+
Version 2.0, January 2004
|
| 8 |
+
https://www.apache.org/licenses/
|
| 9 |
+
|
| 10 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 11 |
+
|
| 12 |
+
1. Definitions.
|
| 13 |
+
|
| 14 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 15 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 16 |
+
|
| 17 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 18 |
+
the copyright owner that is granting the License.
|
| 19 |
+
|
| 20 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 21 |
+
other entities that control, are controlled by, or are under common
|
| 22 |
+
control with that entity. For the purposes of this definition,
|
| 23 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 24 |
+
direction or management of such entity, whether by contract or
|
| 25 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 26 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 27 |
+
|
| 28 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 29 |
+
exercising permissions granted by this License.
|
| 30 |
+
|
| 31 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 32 |
+
including but not limited to software source code, documentation
|
| 33 |
+
source, and configuration files.
|
| 34 |
+
|
| 35 |
+
"Object" form shall mean any form resulting from mechanical
|
| 36 |
+
transformation or translation of a Source form, including but
|
| 37 |
+
not limited to compiled object code, generated documentation,
|
| 38 |
+
and conversions to other media types.
|
| 39 |
+
|
| 40 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 41 |
+
Object form, made available under the License, as indicated by a
|
| 42 |
+
copyright notice that is included in or attached to the work
|
| 43 |
+
(an example is provided in the Appendix below).
|
| 44 |
+
|
| 45 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 46 |
+
form, that is based on (or derived from) the Work and for which the
|
| 47 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 48 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 49 |
+
of this License, Derivative Works shall not include works that remain
|
| 50 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 51 |
+
the Work and Derivative Works thereof.
|
| 52 |
+
|
| 53 |
+
"Contribution" shall mean any work of authorship, including
|
| 54 |
+
the original version of the Work and any modifications or additions
|
| 55 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 56 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 57 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 58 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 59 |
+
means any form of electronic, verbal, or written communication sent
|
| 60 |
+
to the Licensor or its representatives, including but not limited to
|
| 61 |
+
communication on electronic mailing lists, source code control systems,
|
| 62 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 63 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 64 |
+
excluding communication that is conspicuously marked or otherwise
|
| 65 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 66 |
+
|
| 67 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 68 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 69 |
+
subsequently incorporated within the Work.
|
| 70 |
+
|
| 71 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 72 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 73 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 74 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 75 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 76 |
+
Work and such Derivative Works in Source or Object form.
|
| 77 |
+
|
| 78 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 79 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 80 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 81 |
+
(except as stated in this section) patent license to make, have made,
|
| 82 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 83 |
+
where such license applies only to those patent claims licensable
|
| 84 |
+
by such Contributor that are necessarily infringed by their
|
| 85 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 86 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 87 |
+
institute patent litigation against any entity (including a
|
| 88 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 89 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 90 |
+
or contributory patent infringement, then any patent licenses
|
| 91 |
+
granted to You under this License for that Work shall terminate
|
| 92 |
+
as of the date such litigation is filed.
|
| 93 |
+
|
| 94 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 95 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 96 |
+
modifications, and in Source or Object form, provided that You
|
| 97 |
+
meet the following conditions:
|
| 98 |
+
|
| 99 |
+
(a) You must give any other recipients of the Work or
|
| 100 |
+
Derivative Works a copy of this License; and
|
| 101 |
+
|
| 102 |
+
(b) You must cause any modified files to carry prominent notices
|
| 103 |
+
stating that You changed the files; and
|
| 104 |
+
|
| 105 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 106 |
+
that You distribute, all copyright, patent, trademark, and
|
| 107 |
+
attribution notices from the Source form of the Work,
|
| 108 |
+
excluding those notices that do not pertain to any part of
|
| 109 |
+
the Derivative Works; and
|
| 110 |
+
|
| 111 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 112 |
+
distribution, then any Derivative Works that You distribute must
|
| 113 |
+
include a readable copy of the attribution notices contained
|
| 114 |
+
within such NOTICE file, excluding those notices that do not
|
| 115 |
+
pertain to any part of the Derivative Works, in at least one
|
| 116 |
+
of the following places: within a NOTICE text file distributed
|
| 117 |
+
as part of the Derivative Works; within the Source form or
|
| 118 |
+
documentation, if provided along with the Derivative Works; or,
|
| 119 |
+
within a display generated by the Derivative Works, if and
|
| 120 |
+
wherever such third-party notices normally appear. The contents
|
| 121 |
+
of the NOTICE file are for informational purposes only and
|
| 122 |
+
do not modify the License. You may add Your own attribution
|
| 123 |
+
notices within Derivative Works that You distribute, alongside
|
| 124 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 125 |
+
that such additional attribution notices cannot be construed
|
| 126 |
+
as modifying the License.
|
| 127 |
+
|
| 128 |
+
You may add Your own copyright statement to Your modifications and
|
| 129 |
+
may provide additional or different license terms and conditions
|
| 130 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 131 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 132 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 133 |
+
the conditions stated in this License.
|
| 134 |
+
|
| 135 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 136 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 137 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 138 |
+
this License, without any additional terms or conditions.
|
| 139 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 140 |
+
the terms of any separate license agreement you may have executed
|
| 141 |
+
with Licensor regarding such Contributions.
|
| 142 |
+
|
| 143 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 144 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 145 |
+
except as required for reasonable and customary use in describing the
|
| 146 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 147 |
+
|
| 148 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 149 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 150 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 151 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 152 |
+
implied, including, without limitation, any warranties or conditions
|
| 153 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 154 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 155 |
+
appropriateness of using or redistributing the Work and assume any
|
| 156 |
+
risks associated with Your exercise of permissions under this License.
|
| 157 |
+
|
| 158 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 159 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 160 |
+
unless required by applicable law (such as deliberate and grossly
|
| 161 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 162 |
+
liable to You for damages, including any direct, indirect, special,
|
| 163 |
+
incidental, or consequential damages of any character arising as a
|
| 164 |
+
result of this License or out of the use or inability to use the
|
| 165 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 166 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 167 |
+
other commercial damages or losses), even if such Contributor
|
| 168 |
+
has been advised of the possibility of such damages.
|
| 169 |
+
|
| 170 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 171 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 172 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 173 |
+
or other liability obligations and/or rights consistent with this
|
| 174 |
+
License. However, in accepting such obligations, You may act only
|
| 175 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 176 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 177 |
+
defend, and hold each Contributor harmless for any liability
|
| 178 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 179 |
+
of your accepting any such warranty or additional liability.
|
| 180 |
+
|
| 181 |
+
END OF TERMS AND CONDITIONS
|
| 182 |
+
|
| 183 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 184 |
+
|
| 185 |
+
To apply the Apache License to your work, attach the following
|
| 186 |
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
| 187 |
+
replaced with your own identifying information. (Don't include
|
| 188 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 189 |
+
comment syntax for the file format. We also recommend that a
|
| 190 |
+
file or class name and description of purpose be included on the
|
| 191 |
+
same "printed page" as the copyright notice for easier
|
| 192 |
+
identification within third-party archives.
|
| 193 |
+
|
| 194 |
+
Copyright {yyyy} {name of copyright owner}
|
| 195 |
+
|
| 196 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 197 |
+
you may not use this file except in compliance with the License.
|
| 198 |
+
You may obtain a copy of the License at
|
| 199 |
+
|
| 200 |
+
https://www.apache.org/licenses/LICENSE-2.0
|
| 201 |
+
|
| 202 |
+
Unless required by applicable law or agreed to in writing, software
|
| 203 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 204 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 205 |
+
See the License for the specific language governing permissions and
|
| 206 |
+
limitations under the License.
|
| 207 |
+
|
| 208 |
+
Project-URL: Homepage, https://github.com/allenai/OLMo-core
|
| 209 |
+
Project-URL: Documentation, https://olmo-core.readthedocs.io/en/latest/
|
| 210 |
+
Project-URL: Changelog, https://github.com/allenai/OLMo-core/blob/main/CHANGELOG.md
|
| 211 |
+
Requires-Python: >=3.10
|
| 212 |
+
Description-Content-Type: text/markdown
|
| 213 |
+
License-File: LICENSE
|
| 214 |
+
Requires-Dist: numpy
|
| 215 |
+
Requires-Dist: torch>=2.6.0
|
| 216 |
+
Requires-Dist: cached-path>=1.7.2
|
| 217 |
+
Requires-Dist: requests
|
| 218 |
+
Requires-Dist: packaging
|
| 219 |
+
Requires-Dist: rich
|
| 220 |
+
Requires-Dist: omegaconf
|
| 221 |
+
Requires-Dist: safetensors
|
| 222 |
+
Requires-Dist: importlib_resources
|
| 223 |
+
Requires-Dist: bettermap
|
| 224 |
+
Provides-Extra: dev
|
| 225 |
+
Requires-Dist: black<24.0,>=23.1; extra == "dev"
|
| 226 |
+
Requires-Dist: boto3; extra == "dev"
|
| 227 |
+
Requires-Dist: build; extra == "dev"
|
| 228 |
+
Requires-Dist: furo==2024.8.6; extra == "dev"
|
| 229 |
+
Requires-Dist: google-cloud-storage; extra == "dev"
|
| 230 |
+
Requires-Dist: isort<5.14,>=5.12; extra == "dev"
|
| 231 |
+
Requires-Dist: mypy<1.4,>=1.0; extra == "dev"
|
| 232 |
+
Requires-Dist: myst-parser<3.0,>=1.0; extra == "dev"
|
| 233 |
+
Requires-Dist: pytest; extra == "dev"
|
| 234 |
+
Requires-Dist: pytest-memray; extra == "dev"
|
| 235 |
+
Requires-Dist: pytest-sphinx; extra == "dev"
|
| 236 |
+
Requires-Dist: pytest-xdist; extra == "dev"
|
| 237 |
+
Requires-Dist: ruff; extra == "dev"
|
| 238 |
+
Requires-Dist: setuptools; extra == "dev"
|
| 239 |
+
Requires-Dist: Sphinx<=8.1.3,>=6.0; extra == "dev"
|
| 240 |
+
Requires-Dist: sphinx-autobuild; extra == "dev"
|
| 241 |
+
Requires-Dist: sphinx-autodoc-typehints==1.23.3; extra == "dev"
|
| 242 |
+
Requires-Dist: sphinx-copybutton; extra == "dev"
|
| 243 |
+
Requires-Dist: sphinx-inline-tabs; extra == "dev"
|
| 244 |
+
Requires-Dist: twine>=1.11.0; extra == "dev"
|
| 245 |
+
Requires-Dist: wheel; extra == "dev"
|
| 246 |
+
Provides-Extra: beaker
|
| 247 |
+
Requires-Dist: beaker-py<2.0,>=1.37.0; extra == "beaker"
|
| 248 |
+
Requires-Dist: GitPython<4.0,>=3.0; extra == "beaker"
|
| 249 |
+
Requires-Dist: google-cloud-compute; extra == "beaker"
|
| 250 |
+
Provides-Extra: comet
|
| 251 |
+
Requires-Dist: comet_ml; extra == "comet"
|
| 252 |
+
Provides-Extra: eval
|
| 253 |
+
Requires-Dist: ai2-olmo-eval==0.8.5; extra == "eval"
|
| 254 |
+
Provides-Extra: torchao
|
| 255 |
+
Requires-Dist: torchao; extra == "torchao"
|
| 256 |
+
Provides-Extra: transformers
|
| 257 |
+
Requires-Dist: transformers; extra == "transformers"
|
| 258 |
+
Provides-Extra: wandb
|
| 259 |
+
Requires-Dist: wandb; extra == "wandb"
|
| 260 |
+
Provides-Extra: all
|
| 261 |
+
Requires-Dist: ai2-olmo-core[beaker,comet,dev,eval,torchao,transformers,wandb]; extra == "all"
|
| 262 |
+
Dynamic: license-file
|
| 263 |
+
|
| 264 |
+
<div align="center">
|
| 265 |
+
<!-- <img src="https://github.com/allenai/OLMo/assets/8812459/774ac485-a535-4768-8f7c-db7be20f5cc3" width="300"/> -->
|
| 266 |
+
<img src="https://huggingface.co/datasets/allenai/blog-images/resolve/main/olmo2/olmo.png" alt="OLMo Logo" width="280" style="margin-left:'auto' margin-right:'auto' display:'block'"/>
|
| 267 |
+
<br>
|
| 268 |
+
<h1>OLMo-core</h1>
|
| 269 |
+
<h4>Building blocks for OLMo modeling and training</h4>
|
| 270 |
+
</div>
|
| 271 |
+
<p align="center">
|
| 272 |
+
<a href="https://olmo-core.readthedocs.io/en/latest/">
|
| 273 |
+
<img alt="Docs" src="https://img.shields.io/badge/API-docs-red">
|
| 274 |
+
</a>
|
| 275 |
+
<a href="https://github.com/allenai/OLMo-core/tree/main/src/examples">
|
| 276 |
+
<img alt="Examples" src="https://img.shields.io/badge/API-examples-994B00">
|
| 277 |
+
</a>
|
| 278 |
+
<a href="https://github.com/allenai/OLMo-core/releases/tag/v1.9.0">
|
| 279 |
+
<img alt="Pypi" src="https://img.shields.io/pypi/v/ai2-olmo-core.svg">
|
| 280 |
+
</a>
|
| 281 |
+
<a href="https://github.com/allenai/OLMo-core/blob/main/LICENSE">
|
| 282 |
+
<img alt="GitHub License" src="https://img.shields.io/github/license/allenai/OLMo">
|
| 283 |
+
</a>
|
| 284 |
+
<a href="https://arxiv.org/pdf/2501.00656.pdf">
|
| 285 |
+
<img alt="Paper URL" src="https://img.shields.io/badge/arxiv-2402.00838-orange">
|
| 286 |
+
</a>
|
| 287 |
+
<a href="https://playground.allenai.org">
|
| 288 |
+
<img alt="Playground" src="https://img.shields.io/badge/Ai2-Playground-F0529C">
|
| 289 |
+
</a>
|
| 290 |
+
<a href="https://discord.gg/sZq3jTNVNG">
|
| 291 |
+
<img alt="Discord" src="https://img.shields.io/badge/Discord%20-%20blue?style=flat&logo=discord&label=Ai2&color=%235B65E9">
|
| 292 |
+
</a>
|
| 293 |
+
</p>
|
| 294 |
+
|
| 295 |
+
## Installation
|
| 296 |
+
|
| 297 |
+
First install [PyTorch](https://pytorch.org) according to the instructions specific to your operating system and hardware.
|
| 298 |
+
|
| 299 |
+
For development, we recommend installing from source:
|
| 300 |
+
|
| 301 |
+
```bash
|
| 302 |
+
git clone https://github.com/allenai/OLMo-core.git
|
| 303 |
+
cd OLMo-core
|
| 304 |
+
pip install -e .[all]
|
| 305 |
+
```
|
| 306 |
+
Or you can install from PyPI with:
|
| 307 |
+
|
| 308 |
+
```bash
|
| 309 |
+
pip install ai2-olmo-core
|
| 310 |
+
```
|
| 311 |
+
|
| 312 |
+
There are a number of optional dependencies that must be installed to use certain functionality as well, including:
|
| 313 |
+
|
| 314 |
+
- [flash-attn](https://github.com/Dao-AILab/flash-attention), [ring-flash-attn](https://github.com/zhuzilin/ring-flash-attention), and [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) for the corresponding attention backends.
|
| 315 |
+
- [Liger-Kernel](https://github.com/linkedin/Liger-Kernel) for a low-memory "fused-linear" loss implementation.
|
| 316 |
+
- [torchao](https://github.com/pytorch/ao) for float8 training.
|
| 317 |
+
- [grouped_gemm](https://github.com/tgale96/grouped_gemm) for dropless mixture-of-experts (MoE) models. You may need to compile from source until [PR #21](https://github.com/tgale96/grouped_gemm/pull/21) is released (post v0.1.6).
|
| 318 |
+
|
| 319 |
+
The published [Docker images](https://github.com/orgs/allenai/packages?repo_name=OLMo-core) contain all core and optional dependencies, and are regularly tested on our in-house H100 clusters.
|
| 320 |
+
But there are several things to keep in mind if you intend to use these images:
|
| 321 |
+
|
| 322 |
+
- They do not come with the OLMo-core package installed, only its dependencies, to accommodate for regular code changes.
|
| 323 |
+
- They may not work on your own cluster if you have different hardware or driver/CUDA versions.
|
| 324 |
+
|
| 325 |
+
If the published images do not work for your use-case for any of the above reasons, you could adapt our [Dockerfile](https://github.com/allenai/OLMo-core/blob/main/src/Dockerfile) to build your own images.
|
| 326 |
+
|
| 327 |
+
## Official training scripts
|
| 328 |
+
|
| 329 |
+
Official training scripts for released models can be found in [`src/scripts/official/`](https://github.com/allenai/OLMo-core/tree/main/src/scripts/official).
|
| 330 |
+
|
| 331 |
+
These scripts are meant to be launched with ``torchrun``, or with OLMo-core's Beaker launch CLI if you have access to Beaker.
|
| 332 |
+
|
| 333 |
+
For example:
|
| 334 |
+
|
| 335 |
+
```bash
|
| 336 |
+
torchrun --nproc-per-node=8 src/scripts/official/OLMo2/OLMo-2-0325-32B-train.py \
|
| 337 |
+
--save-folder=/path/to/save/checkpoints
|
| 338 |
+
```
|
| 339 |
+
|
| 340 |
+
You can override most configuration options from the command-line. For example, to override the learning rate you could launch the script like this:
|
| 341 |
+
|
| 342 |
+
```bash
|
| 343 |
+
torchrun --nproc-per-node=8 src/scripts/official/OLMo2/OLMo-2-0325-32B-train.py \
|
| 344 |
+
--save-folder=/path/to/save/checkpoints \
|
| 345 |
+
--train_module.optim.lr=6e-3
|
| 346 |
+
```
|
| 347 |
+
|
| 348 |
+
To continue annealing from a checkpoint, we use a separate script which can be launched like this:
|
| 349 |
+
|
| 350 |
+
```bash
|
| 351 |
+
torchrun --nproc-per-node=8 src/scripts/official/OLMo2/OLMo-2-0325-32B-anneal.py \
|
| 352 |
+
--save-folder=/path/to/save/checkpoints \
|
| 353 |
+
--checkpoint=https://olmo-checkpoints.org/ai2-llm/peteish32/step721901
|
| 354 |
+
```
|
| 355 |
+
|
| 356 |
+
### Available Training Scripts
|
| 357 |
+
|
| 358 |
+
| Model Family | Directory | Description |
|
| 359 |
+
|--------------|-----------|-------------|
|
| 360 |
+
| **OLMo-2** | [`src/scripts/official/OLMo2/`](https://github.com/allenai/OLMo-core/tree/main/src/scripts/official/OLMo2) | Training scripts and model card for OLMo-2 32B models |
|
| 361 |
+
| **OLMo-3** | [`src/scripts/official/OLMo3/`](https://github.com/allenai/OLMo-core/tree/main/src/scripts/official/OLMo3) | Training scripts and model cards for OLMo-3 7B and 32B models |
|
| 362 |
+
|
| 363 |
+
## Inference
|
| 364 |
+
|
| 365 |
+
### With Hugging Face Transformers
|
| 366 |
+
|
| 367 |
+
You can use our Hugging Face [transformers](https://github.com/huggingface/transformers) integration to run inference on the OLMo checkpoints:
|
| 368 |
+
|
| 369 |
+
```bash
|
| 370 |
+
pip install transformers>=4.57.0
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
```python
|
| 374 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 375 |
+
olmo = AutoModelForCausalLM.from_pretrained("allenai/Olmo-3-1125-32B")
|
| 376 |
+
tokenizer = AutoTokenizer.from_pretrained("allenai/Olmo-3-1125-32B")
|
| 377 |
+
message = ["Language modeling is "]
|
| 378 |
+
inputs = tokenizer(message, return_tensors='pt', return_token_type_ids=False)
|
| 379 |
+
# inputs = {k: v.to('cuda') for k,v in inputs.items()} # optional verifying cuda
|
| 380 |
+
# olmo = olmo.to('cuda')
|
| 381 |
+
response = olmo.generate(**inputs, max_new_tokens=100, do_sample=True, temperature=1.0, top_p=0.7)
|
| 382 |
+
print(tokenizer.batch_decode(response, skip_special_tokens=True)[0])
|
| 383 |
+
```
|
| 384 |
+
|
| 385 |
+
Alternatively, with the Hugging Face pipeline abstraction:
|
| 386 |
+
|
| 387 |
+
```python
|
| 388 |
+
from transformers import pipeline
|
| 389 |
+
olmo_pipe = pipeline("text-generation", model="allenai/Olmo-3-1125-32B")
|
| 390 |
+
print(olmo_pipe("Language modeling is"))
|
| 391 |
+
```
|
| 392 |
+
|
| 393 |
+
### With vLLM
|
| 394 |
+
|
| 395 |
+
[vLLM](https://docs.vllm.ai/en/latest/) provides high-throughput inference for OLMo models. You can use it for offline batched inference:
|
| 396 |
+
|
| 397 |
+
```bash
|
| 398 |
+
pip install vllm>=0.11.0
|
| 399 |
+
```
|
| 400 |
+
|
| 401 |
+
```python
|
| 402 |
+
from vllm import LLM, SamplingParams
|
| 403 |
+
llm = LLM(model="allenai/Olmo-3-1125-32B")
|
| 404 |
+
sampling_params = SamplingParams(temperature=1.0, top_p=0.7)
|
| 405 |
+
prompts = ["Language modeling is"]
|
| 406 |
+
outputs = llm.generate(prompts, sampling_params)
|
| 407 |
+
for output in outputs:
|
| 408 |
+
prompt = output.prompt
|
| 409 |
+
generated_text = output.outputs[0].text
|
| 410 |
+
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
|
| 411 |
+
```
|
| 412 |
+
|
| 413 |
+
For more details, see the [vLLM documentation](https://docs.vllm.ai/en/latest/getting_started/quickstart/#offline-batched-inference).
|
| 414 |
+
|
| 415 |
+
### With Olmo-core (beta)
|
| 416 |
+
|
| 417 |
+
Autoregressive generation is supported directly in Olmo-core. Using this capability, we provide a chat-loop demo that can be used to interact with models in an interactive chat session:
|
| 418 |
+
|
| 419 |
+
```bash
|
| 420 |
+
python -m olmo_core.generate.chat https://olmo-checkpoints.org/ai2-llm/Olmo-3-1025-7B/stage3/step11921/ --max-new-tokens 512
|
| 421 |
+
```
|
| 422 |
+
|
| 423 |
+
## Evaluation
|
| 424 |
+
|
| 425 |
+
Additional tools for evaluating OLMo models are available at the [OLMo Eval](https://github.com/allenai/OLMo-eval) and [olmes](https://github.com/allenai/olmes) repositories.
|
| 426 |
+
|
| 427 |
+
## Development
|
| 428 |
+
|
| 429 |
+
The Python library source code is located in `src/olmo_core`. The corresponding tests are located in `src/test`. The library docs are located in `docs`. You can build the docs locally with `make docs`.
|
| 430 |
+
|
| 431 |
+
Code checks:
|
| 432 |
+
|
| 433 |
+
- We use `pytest` to run tests. You can run all tests with `pytest -v src/test`. You can also point `pytest` at a specific test file to run it individually.
|
| 434 |
+
- We use `isort` and `black` for code formatting. Ideally you should integrate these into your editor, but you can also run them manually or configure them with a pre-commit hook. To validate that all files are formatted correctly, run `make style-check`.
|
| 435 |
+
- We use `ruff` as our primary linter. You can run it with `make lint-check`.
|
| 436 |
+
- We use `mypy` as our type checker. You can run it with `make type-check`.
|
| 437 |
+
|
| 438 |
+
## Citing
|
| 439 |
+
|
| 440 |
+
```bibtex
|
| 441 |
+
@misc{olmo20242olmo2furious,
|
| 442 |
+
title={{2 OLMo 2 Furious}},
|
| 443 |
+
author={{Team OLMo} and Pete Walsh and Luca Soldaini and Dirk Groeneveld and Kyle Lo and Shane Arora and Akshita Bhagia and Yuling Gu and Shengyi Huang and Matt Jordan and Nathan Lambert and Dustin Schwenk and Oyvind Tafjord and Taira Anderson and David Atkinson and Faeze Brahman and Christopher Clark and Pradeep Dasigi and Nouha Dziri and Michal Guerquin and Hamish Ivison and Pang Wei Koh and Jiacheng Liu and Saumya Malik and William Merrill and Lester James V. Miranda and Jacob Morrison and Tyler Murray and Crystal Nam and Valentina Pyatkin and Aman Rangapur and Michael Schmitz and Sam Skjonsberg and David Wadden and Christopher Wilhelm and Michael Wilson and Luke Zettlemoyer and Ali Farhadi and Noah A. Smith and Hannaneh Hajishirzi},
|
| 444 |
+
year={2024},
|
| 445 |
+
eprint={2501.00656},
|
| 446 |
+
archivePrefix={arXiv},
|
| 447 |
+
primaryClass={cs.CL},
|
| 448 |
+
url={https://arxiv.org/abs/2501.00656},
|
| 449 |
+
}
|
| 450 |
+
```
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ai2_olmo_core-2.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
ai2_olmo_core-2.4.0.dist-info/METADATA,sha256=i79FLpuV65TpzWSuaTGLJhEo0PC35QRqX1B6eq7JMTI,24462
|
| 3 |
+
ai2_olmo_core-2.4.0.dist-info/RECORD,,
|
| 4 |
+
ai2_olmo_core-2.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
| 5 |
+
ai2_olmo_core-2.4.0.dist-info/licenses/LICENSE,sha256=YvuKOpYh3COIF0yqq-nCMXtpS7mh1GyYvPVlW2j1G-M,11359
|
| 6 |
+
ai2_olmo_core-2.4.0.dist-info/top_level.txt,sha256=UtCTFfoX3W7Uv2UKc7h_I8QyTlIAl_fZSZyb7UGwY6Q,10
|
| 7 |
+
olmo_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 8 |
+
olmo_core/__pycache__/__init__.cpython-310.pyc,,
|
| 9 |
+
olmo_core/__pycache__/aliases.cpython-310.pyc,,
|
| 10 |
+
olmo_core/__pycache__/config.cpython-310.pyc,,
|
| 11 |
+
olmo_core/__pycache__/doc_utils.cpython-310.pyc,,
|
| 12 |
+
olmo_core/__pycache__/exceptions.cpython-310.pyc,,
|
| 13 |
+
olmo_core/__pycache__/io.cpython-310.pyc,,
|
| 14 |
+
olmo_core/__pycache__/model_ladder.cpython-310.pyc,,
|
| 15 |
+
olmo_core/__pycache__/script_utils.cpython-310.pyc,,
|
| 16 |
+
olmo_core/__pycache__/utils.cpython-310.pyc,,
|
| 17 |
+
olmo_core/__pycache__/version.cpython-310.pyc,,
|
| 18 |
+
olmo_core/aliases.py,sha256=XWvWxUnmyAlg4lSNLHHATI6Vr1wsw2csndP81UhWVEs,114
|
| 19 |
+
olmo_core/config.py,sha256=VbTYlZ_o_1kMfo1Lcs3ZKvVjfyK8awD1DZsxg3TT_Eg,11632
|
| 20 |
+
olmo_core/data/__init__.py,sha256=OajbGC_Ey1fIS547tj3dWRF7ReEMgJ-iTBzSCUHycVg,2477
|
| 21 |
+
olmo_core/data/__pycache__/__init__.cpython-310.pyc,,
|
| 22 |
+
olmo_core/data/__pycache__/collator.cpython-310.pyc,,
|
| 23 |
+
olmo_core/data/__pycache__/data_loader.cpython-310.pyc,,
|
| 24 |
+
olmo_core/data/__pycache__/numpy_dataset.cpython-310.pyc,,
|
| 25 |
+
olmo_core/data/__pycache__/source_mixture.cpython-310.pyc,,
|
| 26 |
+
olmo_core/data/__pycache__/tokenizer.cpython-310.pyc,,
|
| 27 |
+
olmo_core/data/__pycache__/types.cpython-310.pyc,,
|
| 28 |
+
olmo_core/data/__pycache__/utils.cpython-310.pyc,,
|
| 29 |
+
olmo_core/data/collator.py,sha256=f03Llo96jh2YV7O-L_0LhcAGvZ5GpVfnhDH2fhMKUxU,5537
|
| 30 |
+
olmo_core/data/data_loader.py,sha256=1G6I1X0NN-FS4DwIiFy7IqBq_O894m48XHuQqM_q-vg,45476
|
| 31 |
+
olmo_core/data/mixes/OLMo-longmino-mix-0625.txt,sha256=hWGScM5FrHrdJqaCJKBE2EhYgjtcLDA9Z_TjOYlmf_o,66030
|
| 32 |
+
olmo_core/data/mixes/OLMo-longmino-mix-0925.txt,sha256=HXG_onn3rujGjLCifcvPSgRd5Y4h33fj0Wtcehs9yZs,66216
|
| 33 |
+
olmo_core/data/mixes/OLMo-midtraining-mix-0625-100B.txt,sha256=nnPy6ZbsO6vvDcnzrSS5L19DzYKuIXv3XAKduKit1yA,2359991
|
| 34 |
+
olmo_core/data/mixes/OLMo-midtraining-mix-0925-ingredient1-100B.txt,sha256=XGPAnEvtUvf_2BYwa99ZPRyhgZMwtrrBSW76dsU9v-0,2156993
|
| 35 |
+
olmo_core/data/mixes/OLMo-midtraining-mix-0925-ingredient2-100B.txt,sha256=XGPAnEvtUvf_2BYwa99ZPRyhgZMwtrrBSW76dsU9v-0,2156993
|
| 36 |
+
olmo_core/data/mixes/OLMo-mix-0625-150Bsample.txt,sha256=M-QmjnafVe8EQalmbRi5A2yNLnZdcRykBk6JRwdySj8,870288
|
| 37 |
+
olmo_core/data/mixes/OLMo-mix-0625-700Bsample.txt,sha256=F8yCWQoQImyfK3YhVKsUdu9upzAnSaaD2LTANmlWLDw,30028
|
| 38 |
+
olmo_core/data/mixes/OLMo-mix-0625-official.txt,sha256=13Bxanj-Dp-gdMifAQV0_TTsDudQy3kYgSDGIEfBonA,118078
|
| 39 |
+
olmo_core/data/mixes/OLMo-mix-0625.txt,sha256=t4YWFTmMNYUyNqfU-E5AHrhB4ZwcU5HfoPU01XD5K-Y,116262
|
| 40 |
+
olmo_core/data/mixes/OLMo-mix-0925-official.txt,sha256=5ygDlxunFQ1-z2Jgohq7QIaVO9kV7cuWiB0ueLHeZHE,110287
|
| 41 |
+
olmo_core/data/mixes/OLMo-mix-0925.txt,sha256=_MaoK5pehoiF3s-8MEhpZ2RMfKSCp9aHEC9_9Zfb18k,109962
|
| 42 |
+
olmo_core/data/mixes/OLMoE-mix-0824.txt,sha256=t4S7KjhnrE7LDlS9urh7_v1kgItLXqZJu3HQfwueCg8,120656
|
| 43 |
+
olmo_core/data/mixes/__init__.py,sha256=AsfWpcsdc36396sC0oSsE70XBHtSIyiBNuovSTGc0UE,4989
|
| 44 |
+
olmo_core/data/mixes/__pycache__/__init__.cpython-310.pyc,,
|
| 45 |
+
olmo_core/data/mixes/dolma17.txt,sha256=5csryxCmpE2y-H1wOkGu7O0-eAaqAiITkmOo8J89Gqo,105758
|
| 46 |
+
olmo_core/data/mixes/v3-small-ppl-validation.txt,sha256=P8_jr3sOjrLdTnzPD6Xy-5W0s8FsU9Ocjrou5sVzttE,1050
|
| 47 |
+
olmo_core/data/numpy_dataset.py,sha256=nKwAbtkNOGj-2t_ST8lysD_5CnvX9KsWrkcCd1GVBQQ,111657
|
| 48 |
+
olmo_core/data/source_mixture.py,sha256=u0pAsaTAE3b7LxTGXR3bEKGqExQxUGZG_OAFQzcq1NU,23277
|
| 49 |
+
olmo_core/data/tokenizer.py,sha256=_7HbHE6IfO5ZQiBQcoODKj2-PrFuPXXl0rnwjzGQMAA,3802
|
| 50 |
+
olmo_core/data/types.py,sha256=25OrKLACouQduMoUwJmPZXjErDO0gxIc6WqIt9ygpik,1065
|
| 51 |
+
olmo_core/data/utils.py,sha256=t8xjXBUqSVNViMNKBJo7TdAhrjvbmwJgqQJkE-i3ejg,36437
|
| 52 |
+
olmo_core/distributed/__init__.py,sha256=CacGOPn8um0fqmNB5z4E6uXRCNO52ZasI_ucYrOJojY,76
|
| 53 |
+
olmo_core/distributed/__pycache__/__init__.cpython-310.pyc,,
|
| 54 |
+
olmo_core/distributed/__pycache__/utils.cpython-310.pyc,,
|
| 55 |
+
olmo_core/distributed/checkpoint/__init__.py,sha256=WhIWB-EpiGvJJaw9FG-ZjVN1pQ37pVo1KUpXPQ8fjKw,31596
|
| 56 |
+
olmo_core/distributed/checkpoint/__pycache__/__init__.cpython-310.pyc,,
|
| 57 |
+
olmo_core/distributed/checkpoint/__pycache__/filesystem.cpython-310.pyc,,
|
| 58 |
+
olmo_core/distributed/checkpoint/filesystem.py,sha256=gD9K6tYEeF22880ucVSmLOlEI-HJ6uEHGdMUyUV9fFc,15630
|
| 59 |
+
olmo_core/distributed/parallel/__init__.py,sha256=cNfbyX4UdTLapHZr-Fi_94-tkbIOwcfzgIXBDh8HH4U,20199
|
| 60 |
+
olmo_core/distributed/parallel/__pycache__/__init__.cpython-310.pyc,,
|
| 61 |
+
olmo_core/distributed/parallel/__pycache__/context_parallel.cpython-310.pyc,,
|
| 62 |
+
olmo_core/distributed/parallel/__pycache__/data_parallel.cpython-310.pyc,,
|
| 63 |
+
olmo_core/distributed/parallel/__pycache__/expert_parallel.cpython-310.pyc,,
|
| 64 |
+
olmo_core/distributed/parallel/__pycache__/pipeline_parallel.cpython-310.pyc,,
|
| 65 |
+
olmo_core/distributed/parallel/__pycache__/tensor_parallel.cpython-310.pyc,,
|
| 66 |
+
olmo_core/distributed/parallel/context_parallel.py,sha256=O6c9uSyIRd2kQbh8LIZ_eNehc_5CaSCSFmRFBHjqr5I,243
|
| 67 |
+
olmo_core/distributed/parallel/data_parallel.py,sha256=8uSoVmRGI4zV9KDqtRL_pa2QVPdrpSzBUbhdDLHQFsA,2655
|
| 68 |
+
olmo_core/distributed/parallel/expert_parallel.py,sha256=6pxELsC90UlV2TmtpwXsMkCezqAWGEf67du0TYGZRFI,241
|
| 69 |
+
olmo_core/distributed/parallel/pipeline_parallel.py,sha256=l_Dypo2NWmfjI2-UCVrM13FJvprsUs_EIprRQ6cHEPs,6933
|
| 70 |
+
olmo_core/distributed/parallel/tensor_parallel.py,sha256=M1L70Nj8dYIxRRlrTkfQ54HEfM02xXIzv3CneWmL7oI,2173
|
| 71 |
+
olmo_core/distributed/utils.py,sha256=B1JCXd604jqQV0AaF7HIBg7_y4WI6Qlrax3woSQG4pY,17870
|
| 72 |
+
olmo_core/doc_utils.py,sha256=6p5zoXjR3ozSLsluZSd7pMqodEmPJ_RHZA7yshQK3LA,537
|
| 73 |
+
olmo_core/eval/__init__.py,sha256=ZpvrlpSrgD-Mj_7nnlAilJfqJe2xSQXndluxFsP_dL0,215
|
| 74 |
+
olmo_core/eval/__pycache__/__init__.cpython-310.pyc,,
|
| 75 |
+
olmo_core/eval/__pycache__/evaluator.cpython-310.pyc,,
|
| 76 |
+
olmo_core/eval/__pycache__/lm_evaluator.cpython-310.pyc,,
|
| 77 |
+
olmo_core/eval/__pycache__/metrics.cpython-310.pyc,,
|
| 78 |
+
olmo_core/eval/__pycache__/task_groups.cpython-310.pyc,,
|
| 79 |
+
olmo_core/eval/evaluator.py,sha256=IAEtle6bJFcpNPGmUWv1zxtVkrpltwAvettIQ779YQY,2668
|
| 80 |
+
olmo_core/eval/lm_evaluator.py,sha256=8jMpC5OOdZAA7rct-SViNJLm-5do0o7Ku6WDbPBWPcs,4444
|
| 81 |
+
olmo_core/eval/metrics.py,sha256=SDY9TDklQmVi6zye_1ADtWkAweDL_1XYlG0EPYWCBIo,2807
|
| 82 |
+
olmo_core/eval/task_groups.py,sha256=DKDYST-VfZTcRg5Wamn8TEQn61fWPRZvfgCRBeqP-6Y,5012
|
| 83 |
+
olmo_core/exceptions.py,sha256=xDvUJ_l8G4a2Bqe4hAHxORBFLLh_lQQW8ilOpAf2u3U,641
|
| 84 |
+
olmo_core/float8/__init__.py,sha256=HaTh6amNGemeGxBXrXSlt832NChMw_hA5qhD5sqzlUk,4109
|
| 85 |
+
olmo_core/float8/__pycache__/__init__.cpython-310.pyc,,
|
| 86 |
+
olmo_core/float8/__pycache__/ao.cpython-310.pyc,,
|
| 87 |
+
olmo_core/float8/__pycache__/utils.cpython-310.pyc,,
|
| 88 |
+
olmo_core/float8/ao.py,sha256=Jf1AUHRaLuEfHEUGh0Eph8pRFzAU2lxVbIiSCb6deQ4,3989
|
| 89 |
+
olmo_core/float8/utils.py,sha256=CfrJORwK4CfaEMVUnFuT1ImyQodWCqmiK2lEhrU70BA,1378
|
| 90 |
+
olmo_core/generate/__init__.py,sha256=O7nvnSSGc6krMw2G9H-2pRnqY2utvczF996d4G6hQmc,361
|
| 91 |
+
olmo_core/generate/__pycache__/__init__.cpython-310.pyc,,
|
| 92 |
+
olmo_core/generate/__pycache__/chat.cpython-310.pyc,,
|
| 93 |
+
olmo_core/generate/__pycache__/sampling.cpython-310.pyc,,
|
| 94 |
+
olmo_core/generate/__pycache__/utils.cpython-310.pyc,,
|
| 95 |
+
olmo_core/generate/chat.py,sha256=OvORsvdX2EOL6m_Pb7lUk_OO0ufAZRcjsAiypTJar6U,17664
|
| 96 |
+
olmo_core/generate/generation_module/__init__.py,sha256=SnoUNb-mLD_qAxk6-K4_w431FymUXUTpZz5OwlPlwpc,361
|
| 97 |
+
olmo_core/generate/generation_module/__pycache__/__init__.cpython-310.pyc,,
|
| 98 |
+
olmo_core/generate/generation_module/__pycache__/config.cpython-310.pyc,,
|
| 99 |
+
olmo_core/generate/generation_module/__pycache__/generation_module.cpython-310.pyc,,
|
| 100 |
+
olmo_core/generate/generation_module/config.py,sha256=7roI_q9swvHrgJmADPDdUqAFoHyYGjgTn8rXI4c6rbw,2732
|
| 101 |
+
olmo_core/generate/generation_module/generation_module.py,sha256=PiWHPrLjUHwlGSPnqlJG89Me2lKLcs8Wnh4uAIqny5c,874
|
| 102 |
+
olmo_core/generate/generation_module/transformer/__init__.py,sha256=P0aSMv5nn-MuMWOeBUVt7f2jiEzIp_SzD03Itehm95Y,204
|
| 103 |
+
olmo_core/generate/generation_module/transformer/__pycache__/__init__.cpython-310.pyc,,
|
| 104 |
+
olmo_core/generate/generation_module/transformer/__pycache__/config.cpython-310.pyc,,
|
| 105 |
+
olmo_core/generate/generation_module/transformer/__pycache__/generation_module.cpython-310.pyc,,
|
| 106 |
+
olmo_core/generate/generation_module/transformer/config.py,sha256=4PPXxWqn6JLiaEwqiQmFi3GsaJ_GMesUunCAM8SXiNo,3804
|
| 107 |
+
olmo_core/generate/generation_module/transformer/generation_module.py,sha256=-XBDzm7cDV_6E-qSDfhcKffFjQQZBP90EAaGy17Iv3E,22430
|
| 108 |
+
olmo_core/generate/sampling.py,sha256=5B3-F4EhpL_CS6fkq299bNL-BtN7IRcNnlDPZ4NjW2g,4486
|
| 109 |
+
olmo_core/generate/utils.py,sha256=QHOvt5X1gc_nLdglml9S7ldz-nUutYbpylRdrz9vjzw,793
|
| 110 |
+
olmo_core/internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 111 |
+
olmo_core/internal/__pycache__/__init__.cpython-310.pyc,,
|
| 112 |
+
olmo_core/internal/__pycache__/common.cpython-310.pyc,,
|
| 113 |
+
olmo_core/internal/__pycache__/cookbook.cpython-310.pyc,,
|
| 114 |
+
olmo_core/internal/__pycache__/experiment.cpython-310.pyc,,
|
| 115 |
+
olmo_core/internal/__pycache__/model_ladder.cpython-310.pyc,,
|
| 116 |
+
olmo_core/internal/common.py,sha256=NBhxdN7Av1YhLs6dt3V90ylQx2DLzEw1-SFfY3dAb64,9286
|
| 117 |
+
olmo_core/internal/cookbook.py,sha256=Jxe9j_5vHuJdbxIXA20ywMOYTc-tgfER_ZYhvnpDst4,5486
|
| 118 |
+
olmo_core/internal/experiment.py,sha256=yLDsZ3QR-9hXAjxK6WutoLMVgDjUKNaQJcgvYnQmXgI,20055
|
| 119 |
+
olmo_core/internal/model_ladder.py,sha256=Bl--RFq6eBtW6vrPXdbDyDLh3dWM8UE0ke4NBg3kktI,6425
|
| 120 |
+
olmo_core/io.py,sha256=D0wLVLLjc4kJDUPpiLZL0KOzcVEyhethvOgyZhmZOg4,35990
|
| 121 |
+
olmo_core/kernels/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 122 |
+
olmo_core/kernels/__pycache__/__init__.cpython-310.pyc,,
|
| 123 |
+
olmo_core/kernels/__pycache__/moe.cpython-310.pyc,,
|
| 124 |
+
olmo_core/kernels/moe.py,sha256=s-baQjMwzOHeoqmx3Kr9KhgnGVuBoYyT8LZbgFOhSVE,15947
|
| 125 |
+
olmo_core/launch/__init__.py,sha256=7nvo9YJev0oHqyn4hmxUogGjlzQWicrju5VQxsGjmfU,63
|
| 126 |
+
olmo_core/launch/__pycache__/__init__.cpython-310.pyc,,
|
| 127 |
+
olmo_core/launch/__pycache__/beaker.cpython-310.pyc,,
|
| 128 |
+
olmo_core/launch/__pycache__/reorder_ranks_in_gcp.cpython-310.pyc,,
|
| 129 |
+
olmo_core/launch/__pycache__/select_beaker_hosts.cpython-310.pyc,,
|
| 130 |
+
olmo_core/launch/__pycache__/utils.cpython-310.pyc,,
|
| 131 |
+
olmo_core/launch/beaker.py,sha256=LshGcGhwdjrcyfmDTIxG09nYscEuHCA13VfZKcdAoXk,36455
|
| 132 |
+
olmo_core/launch/reorder_ranks_in_gcp.py,sha256=lON8YzZ83OxCa1N1h_jzaL5e8-y5yWcgpv-APncF67o,4135
|
| 133 |
+
olmo_core/launch/select_beaker_hosts.py,sha256=eBZrOlhaLtMzpZ6RCBXdMkbmY7HJClRk5sHsrlDEcIU,11561
|
| 134 |
+
olmo_core/launch/utils.py,sha256=ERZf3O2yh8a1Da-Rw24LSwoM-kzY6jGYBWHwqHJ8-Es,2663
|
| 135 |
+
olmo_core/model_ladder.py,sha256=oz__aVMPAU7qrquHi7w5dIEHnKDSqYkYoZAlVLEhHFM,15064
|
| 136 |
+
olmo_core/nn/__init__.py,sha256=C1yT4sObTBqoIyRk4dvoRRGB3zLg2mimAE5RlZkIJpQ,57
|
| 137 |
+
olmo_core/nn/__pycache__/__init__.cpython-310.pyc,,
|
| 138 |
+
olmo_core/nn/__pycache__/buffer_cache.cpython-310.pyc,,
|
| 139 |
+
olmo_core/nn/__pycache__/cross_entropy_loss.cpython-310.pyc,,
|
| 140 |
+
olmo_core/nn/__pycache__/feed_forward.cpython-310.pyc,,
|
| 141 |
+
olmo_core/nn/__pycache__/layer_norm.cpython-310.pyc,,
|
| 142 |
+
olmo_core/nn/__pycache__/lm_head.cpython-310.pyc,,
|
| 143 |
+
olmo_core/nn/__pycache__/rope.cpython-310.pyc,,
|
| 144 |
+
olmo_core/nn/__pycache__/utils.cpython-310.pyc,,
|
| 145 |
+
olmo_core/nn/attention/__init__.py,sha256=kQ3-Q9xLTItv0-DkycBIZcd55pxY1yYd73Lct2RbfQs,34442
|
| 146 |
+
olmo_core/nn/attention/__pycache__/__init__.cpython-310.pyc,,
|
| 147 |
+
olmo_core/nn/attention/__pycache__/backend.cpython-310.pyc,,
|
| 148 |
+
olmo_core/nn/attention/__pycache__/flash_attn_api.cpython-310.pyc,,
|
| 149 |
+
olmo_core/nn/attention/__pycache__/kv_cache.cpython-310.pyc,,
|
| 150 |
+
olmo_core/nn/attention/__pycache__/ring.cpython-310.pyc,,
|
| 151 |
+
olmo_core/nn/attention/__pycache__/te_attn_api.cpython-310.pyc,,
|
| 152 |
+
olmo_core/nn/attention/backend.py,sha256=a7UdJhTm52V_1xC2ujNjR6n7KqQ16fifUhw6tuQUA_0,24899
|
| 153 |
+
olmo_core/nn/attention/flash_attn_api.py,sha256=dNxvox4Igc9BXNlJLc2hVjNxPrZgFQWy3w3KmwpH4n0,13539
|
| 154 |
+
olmo_core/nn/attention/kv_cache.py,sha256=juvVDx6hTvK5_3Mfq0HlkgZkcNaSGa6RPmG9W2VlLEs,3863
|
| 155 |
+
olmo_core/nn/attention/ring.py,sha256=HYY44Id3di8PEU_wMj_2-6J_xRmNY2w19YE4Q0LMjkE,13514
|
| 156 |
+
olmo_core/nn/attention/te_attn_api.py,sha256=GueeH9-LKxzqro5a6YkcMn899flRBqQnUV06ig1JyVM,293
|
| 157 |
+
olmo_core/nn/buffer_cache.py,sha256=3MrWKdI0AA4iiQIDqMJyl0HwdByqDg853wgksM_XnT0,2346
|
| 158 |
+
olmo_core/nn/conversion/__init__.py,sha256=uCDzaxrBI8U_m8quzLiWX3DDwWKvGoTmLGT1OvMUoOY,348
|
| 159 |
+
olmo_core/nn/conversion/__pycache__/__init__.cpython-310.pyc,,
|
| 160 |
+
olmo_core/nn/conversion/__pycache__/state_converter.cpython-310.pyc,,
|
| 161 |
+
olmo_core/nn/conversion/__pycache__/state_mapping.cpython-310.pyc,,
|
| 162 |
+
olmo_core/nn/conversion/state_converter.py,sha256=jj4kkvlp1SIb4_HLerLbq_UQ0HGIZqZ_5Pa67t0-QqQ,5674
|
| 163 |
+
olmo_core/nn/conversion/state_mapping.py,sha256=eu_yy8-kIzppPD-rM-ZqZ9dI2-5SYFx7F-rn-kHEWS0,10817
|
| 164 |
+
olmo_core/nn/cross_entropy_loss.py,sha256=bHwy2fN5XjvLVCz7IBdj1dUoXs42iKeSR72LAmtuwfM,7225
|
| 165 |
+
olmo_core/nn/feed_forward.py,sha256=hmbeWHNS3l9SV15Sr1DlFHeKpBvstGOqw8Z55qbt2Ug,7202
|
| 166 |
+
olmo_core/nn/functional/__init__.py,sha256=DAjfYafxKgdUrfgmbMZaLNDaefJb8EfESb-GJhRpfOk,455
|
| 167 |
+
olmo_core/nn/functional/__pycache__/__init__.cpython-310.pyc,,
|
| 168 |
+
olmo_core/nn/functional/__pycache__/cross_entropy_loss.cpython-310.pyc,,
|
| 169 |
+
olmo_core/nn/functional/cross_entropy_loss.py,sha256=i9FnEpKMZmXGmXi0ZoS3rhtQdN-lWyTL80AwPJWoaf0,4505
|
| 170 |
+
olmo_core/nn/hf/__init__.py,sha256=FQfkS3ZdT92Ngrk7fZwUQVcmZdNoL-aZs9g6zjjYSX4,688
|
| 171 |
+
olmo_core/nn/hf/__pycache__/__init__.cpython-310.pyc,,
|
| 172 |
+
olmo_core/nn/hf/__pycache__/checkpoint.cpython-310.pyc,,
|
| 173 |
+
olmo_core/nn/hf/__pycache__/config.cpython-310.pyc,,
|
| 174 |
+
olmo_core/nn/hf/__pycache__/convert.cpython-310.pyc,,
|
| 175 |
+
olmo_core/nn/hf/checkpoint.py,sha256=ghk-_i-nXebpZFKvINQ13ma85kfmKil3G4A2A2NYQng,7429
|
| 176 |
+
olmo_core/nn/hf/config.py,sha256=X4fgfcyZSu6b15vynwmV6iZQbvbkRYRSWcW0vMXV7Tg,9705
|
| 177 |
+
olmo_core/nn/hf/convert.py,sha256=wzVv1_yPRxnpXjPHMd84hwTvQC2-hbX8ZvSka6v5OjU,21361
|
| 178 |
+
olmo_core/nn/layer_norm.py,sha256=tzm4xPhEfi8Hz0o-j3C75Yxb8nTKrTJMssO3FOYgAoM,9184
|
| 179 |
+
olmo_core/nn/lm_head.py,sha256=_cgLUu-egIKVukbWQb2mgQouJ5Uk-LQyP0kfbSX0rg8,19921
|
| 180 |
+
olmo_core/nn/moe/__init__.py,sha256=tPBREjIFac9oYTGIH86r6vgt4dfMscN6ZFP63YOKjZQ,569
|
| 181 |
+
olmo_core/nn/moe/__pycache__/__init__.cpython-310.pyc,,
|
| 182 |
+
olmo_core/nn/moe/__pycache__/loss.cpython-310.pyc,,
|
| 183 |
+
olmo_core/nn/moe/__pycache__/mlp.cpython-310.pyc,,
|
| 184 |
+
olmo_core/nn/moe/__pycache__/moe.cpython-310.pyc,,
|
| 185 |
+
olmo_core/nn/moe/__pycache__/parallel_mlp.cpython-310.pyc,,
|
| 186 |
+
olmo_core/nn/moe/__pycache__/router.cpython-310.pyc,,
|
| 187 |
+
olmo_core/nn/moe/loss.py,sha256=HVZ4fOUFlo5bCNZiLv9AuZ8wnbzx6rjJRrHVvqI5Ucs,5870
|
| 188 |
+
olmo_core/nn/moe/mlp.py,sha256=o6wF6G9iPAL6HLkXXboowbkksy_gl23uMwEJ3rbnbrE,10653
|
| 189 |
+
olmo_core/nn/moe/moe.py,sha256=Q7kAfy84zCY6einPV5SnduLbCMoNDH9PaYpd60GbPYM,12596
|
| 190 |
+
olmo_core/nn/moe/parallel_mlp.py,sha256=FbnMQw3pGfJGW4Xj6g70PT91fdZJvayx3RteK2nuYNM,30351
|
| 191 |
+
olmo_core/nn/moe/router.py,sha256=3ilzo6otNRiNg3gE4Tt1xoKmSgMgex0if4zZcE2I6ZI,21866
|
| 192 |
+
olmo_core/nn/rope.py,sha256=WKhxHlCzo6Q19qsgpcmTYmXhJ2UfNT4iJ5F9SYjSWpg,30870
|
| 193 |
+
olmo_core/nn/transformer/__init__.py,sha256=wMhtrODKXpwcj0K7SopsS6PZgBfaudYhzQxyssPmK1w,1305
|
| 194 |
+
olmo_core/nn/transformer/__pycache__/__init__.cpython-310.pyc,,
|
| 195 |
+
olmo_core/nn/transformer/__pycache__/block.cpython-310.pyc,,
|
| 196 |
+
olmo_core/nn/transformer/__pycache__/config.cpython-310.pyc,,
|
| 197 |
+
olmo_core/nn/transformer/__pycache__/init.cpython-310.pyc,,
|
| 198 |
+
olmo_core/nn/transformer/__pycache__/model.cpython-310.pyc,,
|
| 199 |
+
olmo_core/nn/transformer/block.py,sha256=SVXRnjkZGDuU_WO7Y6xCaSaswvBuYsGq0HuTHnXxUFs,34600
|
| 200 |
+
olmo_core/nn/transformer/config.py,sha256=DwHp5loelJ3bdZkyF_bbWOMcwehLb1fCbghUhY1z3JI,41366
|
| 201 |
+
olmo_core/nn/transformer/init.py,sha256=Zs8OFKdd0QiILqlkDd5HQuNwxiXXQVpdnofiUmMpTiA,6411
|
| 202 |
+
olmo_core/nn/transformer/model.py,sha256=r6m14Vy-C-yX09KKameahjo3ECpvnAgJnW2RagEDmoU,42230
|
| 203 |
+
olmo_core/nn/utils.py,sha256=R6nQHvsRIDcX9gvQqB3gIHaft8s0vP-8NCKuZ7w1M8s,2620
|
| 204 |
+
olmo_core/ops/__init__.py,sha256=OkGQqXX1QquZvb99rNPXuSCMjCSaqdtZHX4nfV2teY4,910
|
| 205 |
+
olmo_core/ops/__pycache__/__init__.cpython-310.pyc,,
|
| 206 |
+
olmo_core/ops/__pycache__/moe.cpython-310.pyc,,
|
| 207 |
+
olmo_core/ops/moe.py,sha256=vsYw3M-yWjw9KVgQTLfPpbjRzdbvYys4Y9lfGPHXoQU,8920
|
| 208 |
+
olmo_core/optim/__init__.py,sha256=JFasWRYyxP3kDzPAco0JsdR4rpN-WtRkTseSH1KJqkQ,1140
|
| 209 |
+
olmo_core/optim/__pycache__/__init__.cpython-310.pyc,,
|
| 210 |
+
olmo_core/optim/__pycache__/adam.cpython-310.pyc,,
|
| 211 |
+
olmo_core/optim/__pycache__/adamw.cpython-310.pyc,,
|
| 212 |
+
olmo_core/optim/__pycache__/config.cpython-310.pyc,,
|
| 213 |
+
olmo_core/optim/__pycache__/lion.cpython-310.pyc,,
|
| 214 |
+
olmo_core/optim/__pycache__/noop.cpython-310.pyc,,
|
| 215 |
+
olmo_core/optim/__pycache__/scheduler.cpython-310.pyc,,
|
| 216 |
+
olmo_core/optim/__pycache__/skip_step_optimizer.cpython-310.pyc,,
|
| 217 |
+
olmo_core/optim/adam.py,sha256=foIBbiK3PlxBdWnHsnIE3gS1F0lVBCLD1oNVEjfL-TM,582
|
| 218 |
+
olmo_core/optim/adamw.py,sha256=jEMwwQOkKbxJItgo1pF3tkTa43xACj6lbPfxy6aB7jw,9410
|
| 219 |
+
olmo_core/optim/config.py,sha256=CwjeoyqnwE-m7ZcaE7BO0fL9ofPo9pMhLK4KKy_vVcM,7224
|
| 220 |
+
olmo_core/optim/lion.py,sha256=6aCDZsTfcZPqsIbuTC5MvgT7xrlbAgiQiihBAdcxyAs,4605
|
| 221 |
+
olmo_core/optim/noop.py,sha256=lr2Qm9ywryZGsmgfCrTD2600iL0cd6p5_N-2qcSTxI8,2836
|
| 222 |
+
olmo_core/optim/scheduler.py,sha256=BfUgIa6WnEqVmTfYFSm-A6O389oX69J6Q1cvMdudnPA,24570
|
| 223 |
+
olmo_core/optim/skip_step_optimizer.py,sha256=kd39C7ldxA7AEEqA75C_h2zuxt26Hg96IECWDtS5ByU,4420
|
| 224 |
+
olmo_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 225 |
+
olmo_core/script_utils.py,sha256=vW9TNEKjg_F1hL_s2cfpXYpuMO5ht5EivsQkQlze92g,6253
|
| 226 |
+
olmo_core/testing/__init__.py,sha256=VVcJChWpn9Zbq-vndjZvyDheDAOMbId4qbVO2qKBA2g,936
|
| 227 |
+
olmo_core/testing/__pycache__/__init__.cpython-310.pyc,,
|
| 228 |
+
olmo_core/testing/__pycache__/distributed.cpython-310.pyc,,
|
| 229 |
+
olmo_core/testing/__pycache__/utils.cpython-310.pyc,,
|
| 230 |
+
olmo_core/testing/distributed.py,sha256=WNZZRssFr7eCIrkqkJL-oSsmW86kDHW3c6TrH2opnJk,3801
|
| 231 |
+
olmo_core/testing/utils.py,sha256=Vfuq8_qbTMqPm-vRXm9FOsK21xQwDCQmEU5zpUxO2Rc,3910
|
| 232 |
+
olmo_core/train/__init__.py,sha256=QllngPRgTyjyNF9GILCfkQ9_w8vZftp6fHHjPCd8oIg,5243
|
| 233 |
+
olmo_core/train/__pycache__/__init__.cpython-310.pyc,,
|
| 234 |
+
olmo_core/train/__pycache__/checkpoint.cpython-310.pyc,,
|
| 235 |
+
olmo_core/train/__pycache__/common.cpython-310.pyc,,
|
| 236 |
+
olmo_core/train/__pycache__/config.cpython-310.pyc,,
|
| 237 |
+
olmo_core/train/__pycache__/trainer.cpython-310.pyc,,
|
| 238 |
+
olmo_core/train/__pycache__/utils.cpython-310.pyc,,
|
| 239 |
+
olmo_core/train/callbacks/__init__.py,sha256=eEN2UiyTRAbCSZTdSFVC216apDW-F1DSeve5dpfYV5w,1903
|
| 240 |
+
olmo_core/train/callbacks/__pycache__/__init__.cpython-310.pyc,,
|
| 241 |
+
olmo_core/train/callbacks/__pycache__/batch_size_scheduler.cpython-310.pyc,,
|
| 242 |
+
olmo_core/train/callbacks/__pycache__/beaker.cpython-310.pyc,,
|
| 243 |
+
olmo_core/train/callbacks/__pycache__/callback.cpython-310.pyc,,
|
| 244 |
+
olmo_core/train/callbacks/__pycache__/checkpointer.cpython-310.pyc,,
|
| 245 |
+
olmo_core/train/callbacks/__pycache__/comet.cpython-310.pyc,,
|
| 246 |
+
olmo_core/train/callbacks/__pycache__/config_saver.cpython-310.pyc,,
|
| 247 |
+
olmo_core/train/callbacks/__pycache__/console_logger.cpython-310.pyc,,
|
| 248 |
+
olmo_core/train/callbacks/__pycache__/evaluator_callback.cpython-310.pyc,,
|
| 249 |
+
olmo_core/train/callbacks/__pycache__/gap_monitor.cpython-310.pyc,,
|
| 250 |
+
olmo_core/train/callbacks/__pycache__/garbage_collector.cpython-310.pyc,,
|
| 251 |
+
olmo_core/train/callbacks/__pycache__/gpu_memory_monitor.cpython-310.pyc,,
|
| 252 |
+
olmo_core/train/callbacks/__pycache__/list_checkpointer.cpython-310.pyc,,
|
| 253 |
+
olmo_core/train/callbacks/__pycache__/monkey_patcher.cpython-310.pyc,,
|
| 254 |
+
olmo_core/train/callbacks/__pycache__/profiler.cpython-310.pyc,,
|
| 255 |
+
olmo_core/train/callbacks/__pycache__/sequence_length_scheduler.cpython-310.pyc,,
|
| 256 |
+
olmo_core/train/callbacks/__pycache__/slack_notifier.cpython-310.pyc,,
|
| 257 |
+
olmo_core/train/callbacks/__pycache__/speed_monitor.cpython-310.pyc,,
|
| 258 |
+
olmo_core/train/callbacks/__pycache__/wandb.cpython-310.pyc,,
|
| 259 |
+
olmo_core/train/callbacks/batch_size_scheduler.py,sha256=cuHEz0Fi_8HHiB2uD9TjoTWP-jv_oC66rtBEnZjCX3I,8966
|
| 260 |
+
olmo_core/train/callbacks/beaker.py,sha256=W_TBzw6VB7RN0pNiSz9V9GQXf_mPbxuswWZ-ltB-bCY,5546
|
| 261 |
+
olmo_core/train/callbacks/callback.py,sha256=z6XAHJq1x-03RD7rY0JdlhhXFFlFAnwoJonQfVH3o7M,4052
|
| 262 |
+
olmo_core/train/callbacks/checkpointer.py,sha256=BA2JqUJ1Yf2bN2M-OHtKhP6qZsjD-k6KAiaPLk-rMNA,10132
|
| 263 |
+
olmo_core/train/callbacks/comet.py,sha256=52Hqep7Ii5BATb1mbgZj5luWap5ez35QlSyhxn1vAtQ,7781
|
| 264 |
+
olmo_core/train/callbacks/config_saver.py,sha256=N1zAfyhQo26Tx0EDPFfTWu670WHynjhy_QOAiT-8s0k,2729
|
| 265 |
+
olmo_core/train/callbacks/console_logger.py,sha256=lLwyD743W3nz_7vQziSG-x0z5MsO-6_lQXAn040Fqi8,2948
|
| 266 |
+
olmo_core/train/callbacks/evaluator_callback.py,sha256=-8wnF55o7TEYutmFCDzR7V0mYKNLNcwTaD_Lb1LwzHA,16473
|
| 267 |
+
olmo_core/train/callbacks/gap_monitor.py,sha256=5mM7m0wYMgLpMiOtXVWwgYcU5wMImTlpSh3qKC6r_XE,7053
|
| 268 |
+
olmo_core/train/callbacks/garbage_collector.py,sha256=mQpq-ssLKPAMSRI6F7nb_VSk5yP5ZiqzE3NqB5Af15U,1426
|
| 269 |
+
olmo_core/train/callbacks/gpu_memory_monitor.py,sha256=fgpMMOFanUPfmWUk5cKZCbcrw6-TZXXEm0JujqMt1gM,2736
|
| 270 |
+
olmo_core/train/callbacks/list_checkpointer.py,sha256=6ur7xPnyEhoUFPe7dOsSNcxpKomG_PJocUrnEXlUeyQ,2035
|
| 271 |
+
olmo_core/train/callbacks/monkey_patcher.py,sha256=d_c1D0MpJJzzMxaOmH5e5gOgZ4oOi6xqnEWNLbG4OtU,694
|
| 272 |
+
olmo_core/train/callbacks/profiler.py,sha256=Nt8osZTWx_h0KgRpXaWIEeSpACRstzUJFgXEm3qlnb4,6579
|
| 273 |
+
olmo_core/train/callbacks/sequence_length_scheduler.py,sha256=A3IiAfrUGWGoiFf6xMJz5YmEAKqXSZQTM3WWG4eFoCU,6675
|
| 274 |
+
olmo_core/train/callbacks/slack_notifier.py,sha256=lnTa5CeBetCrBi1pkPknv2UcKDY-uhHE5rztFmgK3SQ,4339
|
| 275 |
+
olmo_core/train/callbacks/speed_monitor.py,sha256=U3aYwbrhlKb4_nREPM3s00md3Da0LDjA2qHFb37ISdo,6522
|
| 276 |
+
olmo_core/train/callbacks/wandb.py,sha256=vqVhKyrVte-Wl9eF2BmqG3dwGqGqgBQOUsjvXzYDoqo,4851
|
| 277 |
+
olmo_core/train/checkpoint.py,sha256=7x2ntjzM-b27ykGu4YT4axtyajB_Ja30ZmL4P_W5nns,17287
|
| 278 |
+
olmo_core/train/common.py,sha256=KWB5T9ZHf_FqgIlQ0sfujzGCM3jGvR9h1PC62APtG1k,6463
|
| 279 |
+
olmo_core/train/config.py,sha256=aaHb5dyriRDcemMPLiXXG0qmf8oYNRN6mbxxlohKF_4,7100
|
| 280 |
+
olmo_core/train/train_module/__init__.py,sha256=EbKjo69OP7LcCVWXgnTjSf-p6RZFwI3uSjRqfVxIHL8,1190
|
| 281 |
+
olmo_core/train/train_module/__pycache__/__init__.cpython-310.pyc,,
|
| 282 |
+
olmo_core/train/train_module/__pycache__/train_module.cpython-310.pyc,,
|
| 283 |
+
olmo_core/train/train_module/train_module.py,sha256=1FqhHiVA1Ca4cD79fFNX5F9I3nFtAgofa_v22xOrPdM,13599
|
| 284 |
+
olmo_core/train/train_module/transformer/__init__.py,sha256=yAtsjmsc7yZ1Q4mQiEgJZG3CLmyZbM_3j9Nq_E7zf4g,1036
|
| 285 |
+
olmo_core/train/train_module/transformer/__pycache__/__init__.cpython-310.pyc,,
|
| 286 |
+
olmo_core/train/train_module/transformer/__pycache__/common.cpython-310.pyc,,
|
| 287 |
+
olmo_core/train/train_module/transformer/__pycache__/config.cpython-310.pyc,,
|
| 288 |
+
olmo_core/train/train_module/transformer/__pycache__/pipeline_train_module.cpython-310.pyc,,
|
| 289 |
+
olmo_core/train/train_module/transformer/__pycache__/train_module.cpython-310.pyc,,
|
| 290 |
+
olmo_core/train/train_module/transformer/common.py,sha256=1KU_SDadtqyAmaqwHspIj_5DwDqBBLc5u6eTy_HiRfY,6005
|
| 291 |
+
olmo_core/train/train_module/transformer/config.py,sha256=N2kd3R7G9850LutkzTmzCCDjuVRpen2_FbLsl69C_pQ,12230
|
| 292 |
+
olmo_core/train/train_module/transformer/pipeline_train_module.py,sha256=iVkEHz7iMcIj3A9x5wh_Ti44o-bAUnqOWN-j3iin_2I,28412
|
| 293 |
+
olmo_core/train/train_module/transformer/train_module.py,sha256=0hB_BIP7nl7621n3hHLpLqW7-DF-Rz9CRr4OB-oZNow,26638
|
| 294 |
+
olmo_core/train/trainer.py,sha256=n_aUSAUp1RAFRifLMgctyKB3_xp5f1DjhW1hf7vMY6w,52976
|
| 295 |
+
olmo_core/train/utils.py,sha256=KQp10vHsw4wnHuwtmaMadKrWHCIoraAl3OuYdF3kbyY,12830
|
| 296 |
+
olmo_core/utils.py,sha256=Tcg84KbyWn7MxlNjLxXOzCrEl5GNGmWJXtxFF5COleI,22679
|
| 297 |
+
olmo_core/version.py,sha256=RJiyeJ_YuVZ4Lrb0ppk0_e-tttQsSAn5g3MyuHsLEjQ,308
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmo_core-2.4.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
olmo_core
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.3
|
| 2 |
+
Name: annotated-types
|
| 3 |
+
Version: 0.7.0
|
| 4 |
+
Summary: Reusable constraint types to use with typing.Annotated
|
| 5 |
+
Project-URL: Homepage, https://github.com/annotated-types/annotated-types
|
| 6 |
+
Project-URL: Source, https://github.com/annotated-types/annotated-types
|
| 7 |
+
Project-URL: Changelog, https://github.com/annotated-types/annotated-types/releases
|
| 8 |
+
Author-email: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Samuel Colvin <s@muelcolvin.com>, Zac Hatfield-Dodds <zac@zhd.dev>
|
| 9 |
+
License-File: LICENSE
|
| 10 |
+
Classifier: Development Status :: 4 - Beta
|
| 11 |
+
Classifier: Environment :: Console
|
| 12 |
+
Classifier: Environment :: MacOS X
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Intended Audience :: Information Technology
|
| 15 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 16 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 17 |
+
Classifier: Operating System :: Unix
|
| 18 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 24 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 25 |
+
Classifier: Typing :: Typed
|
| 26 |
+
Requires-Python: >=3.8
|
| 27 |
+
Requires-Dist: typing-extensions>=4.0.0; python_version < '3.9'
|
| 28 |
+
Description-Content-Type: text/markdown
|
| 29 |
+
|
| 30 |
+
# annotated-types
|
| 31 |
+
|
| 32 |
+
[](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI)
|
| 33 |
+
[](https://pypi.python.org/pypi/annotated-types)
|
| 34 |
+
[](https://github.com/annotated-types/annotated-types)
|
| 35 |
+
[](https://github.com/annotated-types/annotated-types/blob/main/LICENSE)
|
| 36 |
+
|
| 37 |
+
[PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way of
|
| 38 |
+
adding context-specific metadata to existing types, and specifies that
|
| 39 |
+
`Annotated[T, x]` _should_ be treated as `T` by any tool or library without special
|
| 40 |
+
logic for `x`.
|
| 41 |
+
|
| 42 |
+
This package provides metadata objects which can be used to represent common
|
| 43 |
+
constraints such as upper and lower bounds on scalar values and collection sizes,
|
| 44 |
+
a `Predicate` marker for runtime checks, and
|
| 45 |
+
descriptions of how we intend these metadata to be interpreted. In some cases,
|
| 46 |
+
we also note alternative representations which do not require this package.
|
| 47 |
+
|
| 48 |
+
## Install
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
pip install annotated-types
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
## Examples
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
from typing import Annotated
|
| 58 |
+
from annotated_types import Gt, Len, Predicate
|
| 59 |
+
|
| 60 |
+
class MyClass:
|
| 61 |
+
age: Annotated[int, Gt(18)] # Valid: 19, 20, ...
|
| 62 |
+
# Invalid: 17, 18, "19", 19.0, ...
|
| 63 |
+
factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ...
|
| 64 |
+
# Invalid: 4, 8, -2, 5.0, "prime", ...
|
| 65 |
+
|
| 66 |
+
my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50]
|
| 67 |
+
# Invalid: (1, 2), ["abc"], [0] * 20
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## Documentation
|
| 71 |
+
|
| 72 |
+
_While `annotated-types` avoids runtime checks for performance, users should not
|
| 73 |
+
construct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`.
|
| 74 |
+
Downstream implementors may choose to raise an error, emit a warning, silently ignore
|
| 75 |
+
a metadata item, etc., if the metadata objects described below are used with an
|
| 76 |
+
incompatible type - or for any other reason!_
|
| 77 |
+
|
| 78 |
+
### Gt, Ge, Lt, Le
|
| 79 |
+
|
| 80 |
+
Express inclusive and/or exclusive bounds on orderable values - which may be numbers,
|
| 81 |
+
dates, times, strings, sets, etc. Note that the boundary value need not be of the
|
| 82 |
+
same type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]`
|
| 83 |
+
is fine, for example, and implies that the value is an integer x such that `x > 1.5`.
|
| 84 |
+
|
| 85 |
+
We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)`
|
| 86 |
+
as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency on
|
| 87 |
+
the `annotated-types` package.
|
| 88 |
+
|
| 89 |
+
To be explicit, these types have the following meanings:
|
| 90 |
+
|
| 91 |
+
* `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum
|
| 92 |
+
* `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum
|
| 93 |
+
* `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum
|
| 94 |
+
* `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum
|
| 95 |
+
|
| 96 |
+
### Interval
|
| 97 |
+
|
| 98 |
+
`Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a single
|
| 99 |
+
metadata object. `None` attributes should be ignored, and non-`None` attributes
|
| 100 |
+
treated as per the single bounds above.
|
| 101 |
+
|
| 102 |
+
### MultipleOf
|
| 103 |
+
|
| 104 |
+
`MultipleOf(multiple_of=x)` might be interpreted in two ways:
|
| 105 |
+
|
| 106 |
+
1. Python semantics, implying `value % multiple_of == 0`, or
|
| 107 |
+
2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1),
|
| 108 |
+
where `int(value / multiple_of) == value / multiple_of`.
|
| 109 |
+
|
| 110 |
+
We encourage users to be aware of these two common interpretations and their
|
| 111 |
+
distinct behaviours, especially since very large or non-integer numbers make
|
| 112 |
+
it easy to cause silent data corruption due to floating-point imprecision.
|
| 113 |
+
|
| 114 |
+
We encourage libraries to carefully document which interpretation they implement.
|
| 115 |
+
|
| 116 |
+
### MinLen, MaxLen, Len
|
| 117 |
+
|
| 118 |
+
`Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive.
|
| 119 |
+
|
| 120 |
+
As well as `Len()` which can optionally include upper and lower bounds, we also
|
| 121 |
+
provide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)`
|
| 122 |
+
and `Len(max_length=y)` respectively.
|
| 123 |
+
|
| 124 |
+
`Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`.
|
| 125 |
+
|
| 126 |
+
Examples of usage:
|
| 127 |
+
|
| 128 |
+
* `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10))`) - list must have a length of 10 or less
|
| 129 |
+
* `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less
|
| 130 |
+
* `Annotated[list, MinLen(3))` (or `Annotated[list, Len(min_length=3))`) - list must have a length of 3 or more
|
| 131 |
+
* `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6
|
| 132 |
+
* `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8
|
| 133 |
+
|
| 134 |
+
#### Changed in v0.4.0
|
| 135 |
+
|
| 136 |
+
* `min_inclusive` has been renamed to `min_length`, no change in meaning
|
| 137 |
+
* `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive**
|
| 138 |
+
* The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic
|
| 139 |
+
meaning of the upper bound in slices vs. `Len`
|
| 140 |
+
|
| 141 |
+
See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion.
|
| 142 |
+
|
| 143 |
+
### Timezone
|
| 144 |
+
|
| 145 |
+
`Timezone` can be used with a `datetime` or a `time` to express which timezones
|
| 146 |
+
are allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime.
|
| 147 |
+
`Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis))
|
| 148 |
+
expresses that any timezone-aware datetime is allowed. You may also pass a specific
|
| 149 |
+
timezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects)
|
| 150 |
+
object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you only
|
| 151 |
+
allow a specific timezone, though we note that this is often a symptom of fragile design.
|
| 152 |
+
|
| 153 |
+
#### Changed in v0.x.x
|
| 154 |
+
|
| 155 |
+
* `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of
|
| 156 |
+
`timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries.
|
| 157 |
+
|
| 158 |
+
### Unit
|
| 159 |
+
|
| 160 |
+
`Unit(unit: str)` expresses that the annotated numeric value is the magnitude of
|
| 161 |
+
a quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]`
|
| 162 |
+
would be a float representing a velocity in meters per second.
|
| 163 |
+
|
| 164 |
+
Please note that `annotated_types` itself makes no attempt to parse or validate
|
| 165 |
+
the unit string in any way. That is left entirely to downstream libraries,
|
| 166 |
+
such as [`pint`](https://pint.readthedocs.io) or
|
| 167 |
+
[`astropy.units`](https://docs.astropy.org/en/stable/units/).
|
| 168 |
+
|
| 169 |
+
An example of how a library might use this metadata:
|
| 170 |
+
|
| 171 |
+
```python
|
| 172 |
+
from annotated_types import Unit
|
| 173 |
+
from typing import Annotated, TypeVar, Callable, Any, get_origin, get_args
|
| 174 |
+
|
| 175 |
+
# given a type annotated with a unit:
|
| 176 |
+
Meters = Annotated[float, Unit("m")]
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# you can cast the annotation to a specific unit type with any
|
| 180 |
+
# callable that accepts a string and returns the desired type
|
| 181 |
+
T = TypeVar("T")
|
| 182 |
+
def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None:
|
| 183 |
+
if get_origin(tp) is Annotated:
|
| 184 |
+
for arg in get_args(tp):
|
| 185 |
+
if isinstance(arg, Unit):
|
| 186 |
+
return unit_cls(arg.unit)
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# using `pint`
|
| 191 |
+
import pint
|
| 192 |
+
pint_unit = cast_unit(Meters, pint.Unit)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# using `astropy.units`
|
| 196 |
+
import astropy.units as u
|
| 197 |
+
astropy_unit = cast_unit(Meters, u.Unit)
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
### Predicate
|
| 201 |
+
|
| 202 |
+
`Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values.
|
| 203 |
+
Users should prefer the statically inspectable metadata above, but if you need
|
| 204 |
+
the full power and flexibility of arbitrary runtime predicates... here it is.
|
| 205 |
+
|
| 206 |
+
For some common constraints, we provide generic types:
|
| 207 |
+
|
| 208 |
+
* `IsLower = Annotated[T, Predicate(str.islower)]`
|
| 209 |
+
* `IsUpper = Annotated[T, Predicate(str.isupper)]`
|
| 210 |
+
* `IsDigit = Annotated[T, Predicate(str.isdigit)]`
|
| 211 |
+
* `IsFinite = Annotated[T, Predicate(math.isfinite)]`
|
| 212 |
+
* `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]`
|
| 213 |
+
* `IsNan = Annotated[T, Predicate(math.isnan)]`
|
| 214 |
+
* `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]`
|
| 215 |
+
* `IsInfinite = Annotated[T, Predicate(math.isinf)]`
|
| 216 |
+
* `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]`
|
| 217 |
+
|
| 218 |
+
so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer
|
| 219 |
+
(but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`.
|
| 220 |
+
|
| 221 |
+
Some libraries might have special logic to handle known or understandable predicates,
|
| 222 |
+
for example by checking for `str.isdigit` and using its presence to both call custom
|
| 223 |
+
logic to enforce digit-only strings, and customise some generated external schema.
|
| 224 |
+
Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, in
|
| 225 |
+
favor of introspectable methods such as `str.lower` or `re.compile("pattern").search`.
|
| 226 |
+
|
| 227 |
+
To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner.
|
| 228 |
+
|
| 229 |
+
We do not specify what behaviour should be expected for predicates that raise
|
| 230 |
+
an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
|
| 231 |
+
skip invalid constraints, or statically raise an error; or it might try calling it
|
| 232 |
+
and then propagate or discard the resulting
|
| 233 |
+
`TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object`
|
| 234 |
+
exception. We encourage libraries to document the behaviour they choose.
|
| 235 |
+
|
| 236 |
+
### Doc
|
| 237 |
+
|
| 238 |
+
`doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used.
|
| 239 |
+
|
| 240 |
+
It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools.
|
| 241 |
+
|
| 242 |
+
It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`.
|
| 243 |
+
|
| 244 |
+
This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md).
|
| 245 |
+
|
| 246 |
+
### Integrating downstream types with `GroupedMetadata`
|
| 247 |
+
|
| 248 |
+
Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata.
|
| 249 |
+
This can help reduce verbosity and cognitive overhead for users.
|
| 250 |
+
For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata:
|
| 251 |
+
|
| 252 |
+
```python
|
| 253 |
+
from dataclasses import dataclass
|
| 254 |
+
from typing import Iterator
|
| 255 |
+
from annotated_types import GroupedMetadata, Ge
|
| 256 |
+
|
| 257 |
+
@dataclass
|
| 258 |
+
class Field(GroupedMetadata):
|
| 259 |
+
ge: int | None = None
|
| 260 |
+
description: str | None = None
|
| 261 |
+
|
| 262 |
+
def __iter__(self) -> Iterator[object]:
|
| 263 |
+
# Iterating over a GroupedMetadata object should yield annotated-types
|
| 264 |
+
# constraint metadata objects which describe it as fully as possible,
|
| 265 |
+
# and may include other unknown objects too.
|
| 266 |
+
if self.ge is not None:
|
| 267 |
+
yield Ge(self.ge)
|
| 268 |
+
if self.description is not None:
|
| 269 |
+
yield Description(self.description)
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently.
|
| 273 |
+
|
| 274 |
+
Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself.
|
| 275 |
+
|
| 276 |
+
Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`.
|
| 277 |
+
|
| 278 |
+
### Consuming metadata
|
| 279 |
+
|
| 280 |
+
We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103).
|
| 281 |
+
|
| 282 |
+
It is up to the implementer to determine how this metadata is used.
|
| 283 |
+
You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases.
|
| 284 |
+
|
| 285 |
+
## Design & History
|
| 286 |
+
|
| 287 |
+
This package was designed at the PyCon 2022 sprints by the maintainers of Pydantic
|
| 288 |
+
and Hypothesis, with the goal of making it as easy as possible for end-users to
|
| 289 |
+
provide more informative annotations for use by runtime libraries.
|
| 290 |
+
|
| 291 |
+
It is deliberately minimal, and following PEP-593 allows considerable downstream
|
| 292 |
+
discretion in what (if anything!) they choose to support. Nonetheless, we expect
|
| 293 |
+
that staying simple and covering _only_ the most common use-cases will give users
|
| 294 |
+
and maintainers the best experience we can. If you'd like more constraints for your
|
| 295 |
+
types - follow our lead, by defining them and documenting them downstream!
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
annotated_types-0.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046
|
| 3 |
+
annotated_types-0.7.0.dist-info/RECORD,,
|
| 4 |
+
annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
|
| 5 |
+
annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083
|
| 6 |
+
annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819
|
| 7 |
+
annotated_types/__pycache__/__init__.cpython-310.pyc,,
|
| 8 |
+
annotated_types/__pycache__/test_cases.cpython-310.pyc,,
|
| 9 |
+
annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 10 |
+
annotated_types/test_cases.py,sha256=zHFX6EpcMbGJ8FzBYDbO56bPwx_DYIVSKbZM-4B3_lg,6421
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types-0.7.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.24.2
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/__init__.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import sys
|
| 3 |
+
import types
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from datetime import tzinfo
|
| 6 |
+
from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union
|
| 7 |
+
|
| 8 |
+
if sys.version_info < (3, 8):
|
| 9 |
+
from typing_extensions import Protocol, runtime_checkable
|
| 10 |
+
else:
|
| 11 |
+
from typing import Protocol, runtime_checkable
|
| 12 |
+
|
| 13 |
+
if sys.version_info < (3, 9):
|
| 14 |
+
from typing_extensions import Annotated, Literal
|
| 15 |
+
else:
|
| 16 |
+
from typing import Annotated, Literal
|
| 17 |
+
|
| 18 |
+
if sys.version_info < (3, 10):
|
| 19 |
+
EllipsisType = type(Ellipsis)
|
| 20 |
+
KW_ONLY = {}
|
| 21 |
+
SLOTS = {}
|
| 22 |
+
else:
|
| 23 |
+
from types import EllipsisType
|
| 24 |
+
|
| 25 |
+
KW_ONLY = {"kw_only": True}
|
| 26 |
+
SLOTS = {"slots": True}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = (
|
| 30 |
+
'BaseMetadata',
|
| 31 |
+
'GroupedMetadata',
|
| 32 |
+
'Gt',
|
| 33 |
+
'Ge',
|
| 34 |
+
'Lt',
|
| 35 |
+
'Le',
|
| 36 |
+
'Interval',
|
| 37 |
+
'MultipleOf',
|
| 38 |
+
'MinLen',
|
| 39 |
+
'MaxLen',
|
| 40 |
+
'Len',
|
| 41 |
+
'Timezone',
|
| 42 |
+
'Predicate',
|
| 43 |
+
'LowerCase',
|
| 44 |
+
'UpperCase',
|
| 45 |
+
'IsDigits',
|
| 46 |
+
'IsFinite',
|
| 47 |
+
'IsNotFinite',
|
| 48 |
+
'IsNan',
|
| 49 |
+
'IsNotNan',
|
| 50 |
+
'IsInfinite',
|
| 51 |
+
'IsNotInfinite',
|
| 52 |
+
'doc',
|
| 53 |
+
'DocInfo',
|
| 54 |
+
'__version__',
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
__version__ = '0.7.0'
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
T = TypeVar('T')
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# arguments that start with __ are considered
|
| 64 |
+
# positional only
|
| 65 |
+
# see https://peps.python.org/pep-0484/#positional-only-arguments
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class SupportsGt(Protocol):
|
| 69 |
+
def __gt__(self: T, __other: T) -> bool:
|
| 70 |
+
...
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class SupportsGe(Protocol):
|
| 74 |
+
def __ge__(self: T, __other: T) -> bool:
|
| 75 |
+
...
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class SupportsLt(Protocol):
|
| 79 |
+
def __lt__(self: T, __other: T) -> bool:
|
| 80 |
+
...
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class SupportsLe(Protocol):
|
| 84 |
+
def __le__(self: T, __other: T) -> bool:
|
| 85 |
+
...
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SupportsMod(Protocol):
|
| 89 |
+
def __mod__(self: T, __other: T) -> T:
|
| 90 |
+
...
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class SupportsDiv(Protocol):
|
| 94 |
+
def __div__(self: T, __other: T) -> T:
|
| 95 |
+
...
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class BaseMetadata:
|
| 99 |
+
"""Base class for all metadata.
|
| 100 |
+
|
| 101 |
+
This exists mainly so that implementers
|
| 102 |
+
can do `isinstance(..., BaseMetadata)` while traversing field annotations.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
__slots__ = ()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@dataclass(frozen=True, **SLOTS)
|
| 109 |
+
class Gt(BaseMetadata):
|
| 110 |
+
"""Gt(gt=x) implies that the value must be greater than x.
|
| 111 |
+
|
| 112 |
+
It can be used with any type that supports the ``>`` operator,
|
| 113 |
+
including numbers, dates and times, strings, sets, and so on.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
gt: SupportsGt
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@dataclass(frozen=True, **SLOTS)
|
| 120 |
+
class Ge(BaseMetadata):
|
| 121 |
+
"""Ge(ge=x) implies that the value must be greater than or equal to x.
|
| 122 |
+
|
| 123 |
+
It can be used with any type that supports the ``>=`` operator,
|
| 124 |
+
including numbers, dates and times, strings, sets, and so on.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
ge: SupportsGe
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@dataclass(frozen=True, **SLOTS)
|
| 131 |
+
class Lt(BaseMetadata):
|
| 132 |
+
"""Lt(lt=x) implies that the value must be less than x.
|
| 133 |
+
|
| 134 |
+
It can be used with any type that supports the ``<`` operator,
|
| 135 |
+
including numbers, dates and times, strings, sets, and so on.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
lt: SupportsLt
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@dataclass(frozen=True, **SLOTS)
|
| 142 |
+
class Le(BaseMetadata):
|
| 143 |
+
"""Le(le=x) implies that the value must be less than or equal to x.
|
| 144 |
+
|
| 145 |
+
It can be used with any type that supports the ``<=`` operator,
|
| 146 |
+
including numbers, dates and times, strings, sets, and so on.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
le: SupportsLe
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@runtime_checkable
|
| 153 |
+
class GroupedMetadata(Protocol):
|
| 154 |
+
"""A grouping of multiple objects, like typing.Unpack.
|
| 155 |
+
|
| 156 |
+
`GroupedMetadata` on its own is not metadata and has no meaning.
|
| 157 |
+
All of the constraints and metadata should be fully expressable
|
| 158 |
+
in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`.
|
| 159 |
+
|
| 160 |
+
Concrete implementations should override `GroupedMetadata.__iter__()`
|
| 161 |
+
to add their own metadata.
|
| 162 |
+
For example:
|
| 163 |
+
|
| 164 |
+
>>> @dataclass
|
| 165 |
+
>>> class Field(GroupedMetadata):
|
| 166 |
+
>>> gt: float | None = None
|
| 167 |
+
>>> description: str | None = None
|
| 168 |
+
...
|
| 169 |
+
>>> def __iter__(self) -> Iterable[object]:
|
| 170 |
+
>>> if self.gt is not None:
|
| 171 |
+
>>> yield Gt(self.gt)
|
| 172 |
+
>>> if self.description is not None:
|
| 173 |
+
>>> yield Description(self.gt)
|
| 174 |
+
|
| 175 |
+
Also see the implementation of `Interval` below for an example.
|
| 176 |
+
|
| 177 |
+
Parsers should recognize this and unpack it so that it can be used
|
| 178 |
+
both with and without unpacking:
|
| 179 |
+
|
| 180 |
+
- `Annotated[int, Field(...)]` (parser must unpack Field)
|
| 181 |
+
- `Annotated[int, *Field(...)]` (PEP-646)
|
| 182 |
+
""" # noqa: trailing-whitespace
|
| 183 |
+
|
| 184 |
+
@property
|
| 185 |
+
def __is_annotated_types_grouped_metadata__(self) -> Literal[True]:
|
| 186 |
+
return True
|
| 187 |
+
|
| 188 |
+
def __iter__(self) -> Iterator[object]:
|
| 189 |
+
...
|
| 190 |
+
|
| 191 |
+
if not TYPE_CHECKING:
|
| 192 |
+
__slots__ = () # allow subclasses to use slots
|
| 193 |
+
|
| 194 |
+
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
|
| 195 |
+
# Basic ABC like functionality without the complexity of an ABC
|
| 196 |
+
super().__init_subclass__(*args, **kwargs)
|
| 197 |
+
if cls.__iter__ is GroupedMetadata.__iter__:
|
| 198 |
+
raise TypeError("Can't subclass GroupedMetadata without implementing __iter__")
|
| 199 |
+
|
| 200 |
+
def __iter__(self) -> Iterator[object]: # noqa: F811
|
| 201 |
+
raise NotImplementedError # more helpful than "None has no attribute..." type errors
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
@dataclass(frozen=True, **KW_ONLY, **SLOTS)
|
| 205 |
+
class Interval(GroupedMetadata):
|
| 206 |
+
"""Interval can express inclusive or exclusive bounds with a single object.
|
| 207 |
+
|
| 208 |
+
It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which
|
| 209 |
+
are interpreted the same way as the single-bound constraints.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
gt: Union[SupportsGt, None] = None
|
| 213 |
+
ge: Union[SupportsGe, None] = None
|
| 214 |
+
lt: Union[SupportsLt, None] = None
|
| 215 |
+
le: Union[SupportsLe, None] = None
|
| 216 |
+
|
| 217 |
+
def __iter__(self) -> Iterator[BaseMetadata]:
|
| 218 |
+
"""Unpack an Interval into zero or more single-bounds."""
|
| 219 |
+
if self.gt is not None:
|
| 220 |
+
yield Gt(self.gt)
|
| 221 |
+
if self.ge is not None:
|
| 222 |
+
yield Ge(self.ge)
|
| 223 |
+
if self.lt is not None:
|
| 224 |
+
yield Lt(self.lt)
|
| 225 |
+
if self.le is not None:
|
| 226 |
+
yield Le(self.le)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@dataclass(frozen=True, **SLOTS)
|
| 230 |
+
class MultipleOf(BaseMetadata):
|
| 231 |
+
"""MultipleOf(multiple_of=x) might be interpreted in two ways:
|
| 232 |
+
|
| 233 |
+
1. Python semantics, implying ``value % multiple_of == 0``, or
|
| 234 |
+
2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of``
|
| 235 |
+
|
| 236 |
+
We encourage users to be aware of these two common interpretations,
|
| 237 |
+
and libraries to carefully document which they implement.
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
multiple_of: Union[SupportsDiv, SupportsMod]
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@dataclass(frozen=True, **SLOTS)
|
| 244 |
+
class MinLen(BaseMetadata):
|
| 245 |
+
"""
|
| 246 |
+
MinLen() implies minimum inclusive length,
|
| 247 |
+
e.g. ``len(value) >= min_length``.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
min_length: Annotated[int, Ge(0)]
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@dataclass(frozen=True, **SLOTS)
|
| 254 |
+
class MaxLen(BaseMetadata):
|
| 255 |
+
"""
|
| 256 |
+
MaxLen() implies maximum inclusive length,
|
| 257 |
+
e.g. ``len(value) <= max_length``.
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
max_length: Annotated[int, Ge(0)]
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@dataclass(frozen=True, **SLOTS)
|
| 264 |
+
class Len(GroupedMetadata):
|
| 265 |
+
"""
|
| 266 |
+
Len() implies that ``min_length <= len(value) <= max_length``.
|
| 267 |
+
|
| 268 |
+
Upper bound may be omitted or ``None`` to indicate no upper length bound.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
min_length: Annotated[int, Ge(0)] = 0
|
| 272 |
+
max_length: Optional[Annotated[int, Ge(0)]] = None
|
| 273 |
+
|
| 274 |
+
def __iter__(self) -> Iterator[BaseMetadata]:
|
| 275 |
+
"""Unpack a Len into zone or more single-bounds."""
|
| 276 |
+
if self.min_length > 0:
|
| 277 |
+
yield MinLen(self.min_length)
|
| 278 |
+
if self.max_length is not None:
|
| 279 |
+
yield MaxLen(self.max_length)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
@dataclass(frozen=True, **SLOTS)
|
| 283 |
+
class Timezone(BaseMetadata):
|
| 284 |
+
"""Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive).
|
| 285 |
+
|
| 286 |
+
``Annotated[datetime, Timezone(None)]`` must be a naive datetime.
|
| 287 |
+
``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be
|
| 288 |
+
tz-aware but any timezone is allowed.
|
| 289 |
+
|
| 290 |
+
You may also pass a specific timezone string or tzinfo object such as
|
| 291 |
+
``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that
|
| 292 |
+
you only allow a specific timezone, though we note that this is often
|
| 293 |
+
a symptom of poor design.
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
tz: Union[str, tzinfo, EllipsisType, None]
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
@dataclass(frozen=True, **SLOTS)
|
| 300 |
+
class Unit(BaseMetadata):
|
| 301 |
+
"""Indicates that the value is a physical quantity with the specified unit.
|
| 302 |
+
|
| 303 |
+
It is intended for usage with numeric types, where the value represents the
|
| 304 |
+
magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]``
|
| 305 |
+
or ``speed: Annotated[float, Unit('m/s')]``.
|
| 306 |
+
|
| 307 |
+
Interpretation of the unit string is left to the discretion of the consumer.
|
| 308 |
+
It is suggested to follow conventions established by python libraries that work
|
| 309 |
+
with physical quantities, such as
|
| 310 |
+
|
| 311 |
+
- ``pint`` : <https://pint.readthedocs.io/en/stable/>
|
| 312 |
+
- ``astropy.units``: <https://docs.astropy.org/en/stable/units/>
|
| 313 |
+
|
| 314 |
+
For indicating a quantity with a certain dimensionality but without a specific unit
|
| 315 |
+
it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`.
|
| 316 |
+
Note, however, ``annotated_types`` itself makes no use of the unit string.
|
| 317 |
+
"""
|
| 318 |
+
|
| 319 |
+
unit: str
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@dataclass(frozen=True, **SLOTS)
|
| 323 |
+
class Predicate(BaseMetadata):
|
| 324 |
+
"""``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values.
|
| 325 |
+
|
| 326 |
+
Users should prefer statically inspectable metadata, but if you need the full
|
| 327 |
+
power and flexibility of arbitrary runtime predicates... here it is.
|
| 328 |
+
|
| 329 |
+
We provide a few predefined predicates for common string constraints:
|
| 330 |
+
``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and
|
| 331 |
+
``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which
|
| 332 |
+
can be given special handling, and avoid indirection like ``lambda s: s.lower()``.
|
| 333 |
+
|
| 334 |
+
Some libraries might have special logic to handle certain predicates, e.g. by
|
| 335 |
+
checking for `str.isdigit` and using its presence to both call custom logic to
|
| 336 |
+
enforce digit-only strings, and customise some generated external schema.
|
| 337 |
+
|
| 338 |
+
We do not specify what behaviour should be expected for predicates that raise
|
| 339 |
+
an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
|
| 340 |
+
skip invalid constraints, or statically raise an error; or it might try calling it
|
| 341 |
+
and then propagate or discard the resulting exception.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
func: Callable[[Any], bool]
|
| 345 |
+
|
| 346 |
+
def __repr__(self) -> str:
|
| 347 |
+
if getattr(self.func, "__name__", "<lambda>") == "<lambda>":
|
| 348 |
+
return f"{self.__class__.__name__}({self.func!r})"
|
| 349 |
+
if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and (
|
| 350 |
+
namespace := getattr(self.func.__self__, "__name__", None)
|
| 351 |
+
):
|
| 352 |
+
return f"{self.__class__.__name__}({namespace}.{self.func.__name__})"
|
| 353 |
+
if isinstance(self.func, type(str.isascii)): # method descriptor
|
| 354 |
+
return f"{self.__class__.__name__}({self.func.__qualname__})"
|
| 355 |
+
return f"{self.__class__.__name__}({self.func.__name__})"
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@dataclass
|
| 359 |
+
class Not:
|
| 360 |
+
func: Callable[[Any], bool]
|
| 361 |
+
|
| 362 |
+
def __call__(self, __v: Any) -> bool:
|
| 363 |
+
return not self.func(__v)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
_StrType = TypeVar("_StrType", bound=str)
|
| 367 |
+
|
| 368 |
+
LowerCase = Annotated[_StrType, Predicate(str.islower)]
|
| 369 |
+
"""
|
| 370 |
+
Return True if the string is a lowercase string, False otherwise.
|
| 371 |
+
|
| 372 |
+
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
|
| 373 |
+
""" # noqa: E501
|
| 374 |
+
UpperCase = Annotated[_StrType, Predicate(str.isupper)]
|
| 375 |
+
"""
|
| 376 |
+
Return True if the string is an uppercase string, False otherwise.
|
| 377 |
+
|
| 378 |
+
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
|
| 379 |
+
""" # noqa: E501
|
| 380 |
+
IsDigit = Annotated[_StrType, Predicate(str.isdigit)]
|
| 381 |
+
IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63
|
| 382 |
+
"""
|
| 383 |
+
Return True if the string is a digit string, False otherwise.
|
| 384 |
+
|
| 385 |
+
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
|
| 386 |
+
""" # noqa: E501
|
| 387 |
+
IsAscii = Annotated[_StrType, Predicate(str.isascii)]
|
| 388 |
+
"""
|
| 389 |
+
Return True if all characters in the string are ASCII, False otherwise.
|
| 390 |
+
|
| 391 |
+
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
|
| 392 |
+
"""
|
| 393 |
+
|
| 394 |
+
_NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex])
|
| 395 |
+
IsFinite = Annotated[_NumericType, Predicate(math.isfinite)]
|
| 396 |
+
"""Return True if x is neither an infinity nor a NaN, and False otherwise."""
|
| 397 |
+
IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))]
|
| 398 |
+
"""Return True if x is one of infinity or NaN, and False otherwise"""
|
| 399 |
+
IsNan = Annotated[_NumericType, Predicate(math.isnan)]
|
| 400 |
+
"""Return True if x is a NaN (not a number), and False otherwise."""
|
| 401 |
+
IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))]
|
| 402 |
+
"""Return True if x is anything but NaN (not a number), and False otherwise."""
|
| 403 |
+
IsInfinite = Annotated[_NumericType, Predicate(math.isinf)]
|
| 404 |
+
"""Return True if x is a positive or negative infinity, and False otherwise."""
|
| 405 |
+
IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))]
|
| 406 |
+
"""Return True if x is neither a positive or negative infinity, and False otherwise."""
|
| 407 |
+
|
| 408 |
+
try:
|
| 409 |
+
from typing_extensions import DocInfo, doc # type: ignore [attr-defined]
|
| 410 |
+
except ImportError:
|
| 411 |
+
|
| 412 |
+
@dataclass(frozen=True, **SLOTS)
|
| 413 |
+
class DocInfo: # type: ignore [no-redef]
|
| 414 |
+
""" "
|
| 415 |
+
The return value of doc(), mainly to be used by tools that want to extract the
|
| 416 |
+
Annotated documentation at runtime.
|
| 417 |
+
"""
|
| 418 |
+
|
| 419 |
+
documentation: str
|
| 420 |
+
"""The documentation string passed to doc()."""
|
| 421 |
+
|
| 422 |
+
def doc(
|
| 423 |
+
documentation: str,
|
| 424 |
+
) -> DocInfo:
|
| 425 |
+
"""
|
| 426 |
+
Add documentation to a type annotation inside of Annotated.
|
| 427 |
+
|
| 428 |
+
For example:
|
| 429 |
+
|
| 430 |
+
>>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ...
|
| 431 |
+
"""
|
| 432 |
+
return DocInfo(documentation)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/py.typed
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/annotated_types/test_cases.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import sys
|
| 3 |
+
from datetime import date, datetime, timedelta, timezone
|
| 4 |
+
from decimal import Decimal
|
| 5 |
+
from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple
|
| 6 |
+
|
| 7 |
+
if sys.version_info < (3, 9):
|
| 8 |
+
from typing_extensions import Annotated
|
| 9 |
+
else:
|
| 10 |
+
from typing import Annotated
|
| 11 |
+
|
| 12 |
+
import annotated_types as at
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Case(NamedTuple):
|
| 16 |
+
"""
|
| 17 |
+
A test case for `annotated_types`.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
annotation: Any
|
| 21 |
+
valid_cases: Iterable[Any]
|
| 22 |
+
invalid_cases: Iterable[Any]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def cases() -> Iterable[Case]:
|
| 26 |
+
# Gt, Ge, Lt, Le
|
| 27 |
+
yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1))
|
| 28 |
+
yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1))
|
| 29 |
+
yield Case(
|
| 30 |
+
Annotated[datetime, at.Gt(datetime(2000, 1, 1))],
|
| 31 |
+
[datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 32 |
+
[datetime(2000, 1, 1), datetime(1999, 12, 31)],
|
| 33 |
+
)
|
| 34 |
+
yield Case(
|
| 35 |
+
Annotated[datetime, at.Gt(date(2000, 1, 1))],
|
| 36 |
+
[date(2000, 1, 2), date(2000, 1, 3)],
|
| 37 |
+
[date(2000, 1, 1), date(1999, 12, 31)],
|
| 38 |
+
)
|
| 39 |
+
yield Case(
|
| 40 |
+
Annotated[datetime, at.Gt(Decimal('1.123'))],
|
| 41 |
+
[Decimal('1.1231'), Decimal('123')],
|
| 42 |
+
[Decimal('1.123'), Decimal('0')],
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1))
|
| 46 |
+
yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1))
|
| 47 |
+
yield Case(
|
| 48 |
+
Annotated[datetime, at.Ge(datetime(2000, 1, 1))],
|
| 49 |
+
[datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 50 |
+
[datetime(1998, 1, 1), datetime(1999, 12, 31)],
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4))
|
| 54 |
+
yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9))
|
| 55 |
+
yield Case(
|
| 56 |
+
Annotated[datetime, at.Lt(datetime(2000, 1, 1))],
|
| 57 |
+
[datetime(1999, 12, 31), datetime(1999, 12, 31)],
|
| 58 |
+
[datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000))
|
| 62 |
+
yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9))
|
| 63 |
+
yield Case(
|
| 64 |
+
Annotated[datetime, at.Le(datetime(2000, 1, 1))],
|
| 65 |
+
[datetime(2000, 1, 1), datetime(1999, 12, 31)],
|
| 66 |
+
[datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# Interval
|
| 70 |
+
yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1))
|
| 71 |
+
yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1))
|
| 72 |
+
yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1))
|
| 73 |
+
yield Case(
|
| 74 |
+
Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))],
|
| 75 |
+
[datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 76 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 4)],
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4))
|
| 80 |
+
yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1))
|
| 81 |
+
|
| 82 |
+
# lengths
|
| 83 |
+
|
| 84 |
+
yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
|
| 85 |
+
yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
|
| 86 |
+
yield Case(Annotated[List[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
|
| 87 |
+
yield Case(Annotated[List[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
|
| 88 |
+
|
| 89 |
+
yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10))
|
| 90 |
+
yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10))
|
| 91 |
+
yield Case(Annotated[List[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
|
| 92 |
+
yield Case(Annotated[List[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
|
| 93 |
+
|
| 94 |
+
yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10))
|
| 95 |
+
yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234'))
|
| 96 |
+
|
| 97 |
+
yield Case(Annotated[Dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}])
|
| 98 |
+
yield Case(Annotated[Set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4}))
|
| 99 |
+
yield Case(Annotated[Tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4)))
|
| 100 |
+
|
| 101 |
+
# Timezone
|
| 102 |
+
|
| 103 |
+
yield Case(
|
| 104 |
+
Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)]
|
| 105 |
+
)
|
| 106 |
+
yield Case(
|
| 107 |
+
Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)]
|
| 108 |
+
)
|
| 109 |
+
yield Case(
|
| 110 |
+
Annotated[datetime, at.Timezone(timezone.utc)],
|
| 111 |
+
[datetime(2000, 1, 1, tzinfo=timezone.utc)],
|
| 112 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
|
| 113 |
+
)
|
| 114 |
+
yield Case(
|
| 115 |
+
Annotated[datetime, at.Timezone('Europe/London')],
|
| 116 |
+
[datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))],
|
| 117 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# Quantity
|
| 121 |
+
|
| 122 |
+
yield Case(Annotated[float, at.Unit(unit='m')], (5, 4.2), ('5m', '4.2m'))
|
| 123 |
+
|
| 124 |
+
# predicate types
|
| 125 |
+
|
| 126 |
+
yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom'])
|
| 127 |
+
yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC'])
|
| 128 |
+
yield Case(at.IsDigit[str], ['123'], ['', 'ab', 'a1b2'])
|
| 129 |
+
yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀'])
|
| 130 |
+
|
| 131 |
+
yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5])
|
| 132 |
+
|
| 133 |
+
yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf])
|
| 134 |
+
yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23])
|
| 135 |
+
yield Case(at.IsNan[float], [math.nan], [1.23, math.inf])
|
| 136 |
+
yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan])
|
| 137 |
+
yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23])
|
| 138 |
+
yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf])
|
| 139 |
+
|
| 140 |
+
# check stacked predicates
|
| 141 |
+
yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan])
|
| 142 |
+
|
| 143 |
+
# doc
|
| 144 |
+
yield Case(Annotated[int, at.doc("A number")], [1, 2], [])
|
| 145 |
+
|
| 146 |
+
# custom GroupedMetadata
|
| 147 |
+
class MyCustomGroupedMetadata(at.GroupedMetadata):
|
| 148 |
+
def __iter__(self) -> Iterator[at.Predicate]:
|
| 149 |
+
yield at.Predicate(lambda x: float(x).is_integer())
|
| 150 |
+
|
| 151 |
+
yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5])
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: antlr4-python3-runtime
|
| 3 |
+
Version: 4.11.0
|
| 4 |
+
Summary: ANTLR 4.11.0 runtime for Python 3
|
| 5 |
+
Home-page: http://www.antlr.org
|
| 6 |
+
Author: Eric Vergnaud, Terence Parr, Sam Harwell
|
| 7 |
+
Author-email: eric.vergnaud@wanadoo.fr
|
| 8 |
+
License: BSD
|
| 9 |
+
Requires-Dist: typing ; python_version < "3.5"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1Dv3IphsxFu8nwWdLeXYcqJ8CC5yHwjH8,2110
|
| 4 |
+
antlr4/CommonTokenStream.py,sha256=NNJHXwRg2_Zn46ZhJyDxZtvZzsPWhb6JjXa7BjM45eg,2770
|
| 5 |
+
antlr4/FileStream.py,sha256=-ZR_-jl_If9IIBYLINIwlQrlTSmu5k1VUKDc3ie7WR4,868
|
| 6 |
+
antlr4/InputStream.py,sha256=sggjE2jEGvSgQmxFvqeeuT3aOVgcH5tS7mMybW8wKS4,2334
|
| 7 |
+
antlr4/IntervalSet.py,sha256=Cd0WKhd_kYbiLYKkDNncgSM19GAuS7OaTOC4-5Yubs4,5965
|
| 8 |
+
antlr4/LL1Analyzer.py,sha256=oJBvO7_S8cAlb_D4qWNxd2IlK0qP4ka-oeoDxx16CZ4,7752
|
| 9 |
+
antlr4/Lexer.py,sha256=C72hqayfkympxb46AcSnhPD9kVZ0quWgboGxa6gcIcg,11542
|
| 10 |
+
antlr4/ListTokenSource.py,sha256=IffLMo7YQnD_CjKryrrgNWSk0q5QSYd7puZyyUk7vOk,5356
|
| 11 |
+
antlr4/Parser.py,sha256=F2Q25z0-__KHfa354KQhDu3ZOVzLFfag3s2ixJ4dl_o,22883
|
| 12 |
+
antlr4/ParserInterpreter.py,sha256=-QU9kn4x3WCQ-LSA99R231HoicTqakiHZ5KM72l-hIo,7206
|
| 13 |
+
antlr4/ParserRuleContext.py,sha256=wHAVdOxMAO5jkUqloTXVzn_xYnJhiHbvvuhZpth0ZF8,6762
|
| 14 |
+
antlr4/PredictionContext.py,sha256=cb4KI6EGpS7sRzJ8UvPEkxphINZuWhyiZ95752g3prI,22977
|
| 15 |
+
antlr4/Recognizer.py,sha256=tMXl-YTlUqLYXfYTfQy7fUX9V5KKXEO96WBTdAb3dgk,5384
|
| 16 |
+
antlr4/RuleContext.py,sha256=GiviRv2k_al1IBgdJOEEoD0ohJaVd-_h5T_CPG_Bsmg,8099
|
| 17 |
+
antlr4/StdinStream.py,sha256=MMSH4zN8T6i_nu-3_TlN-3E4nPM4b5KgK4GT6n_FUQA,303
|
| 18 |
+
antlr4/Token.py,sha256=OtWCab4Ut52X_nLLAA-8x4Zl6xaF6TEN-0033uaoaEo,5206
|
| 19 |
+
antlr4/TokenStreamRewriter.py,sha256=cuErQTrXwC_0kqVv3MsTWGZSm-E1Vy1yzA-3SOhKd_s,10324
|
| 20 |
+
antlr4/Utils.py,sha256=Oyg8CJCRL1TrF_QSB_LLlVdWOB4loVcKOgFNT-icO7c,931
|
| 21 |
+
antlr4/__init__.py,sha256=g8UGpflnlMWcAyLtihejzrgAP1Uo3b9GhwfI8QnZjtw,1125
|
| 22 |
+
antlr4/__pycache__/BufferedTokenStream.cpython-310.pyc,,
|
| 23 |
+
antlr4/__pycache__/CommonTokenFactory.cpython-310.pyc,,
|
| 24 |
+
antlr4/__pycache__/CommonTokenStream.cpython-310.pyc,,
|
| 25 |
+
antlr4/__pycache__/FileStream.cpython-310.pyc,,
|
| 26 |
+
antlr4/__pycache__/InputStream.cpython-310.pyc,,
|
| 27 |
+
antlr4/__pycache__/IntervalSet.cpython-310.pyc,,
|
| 28 |
+
antlr4/__pycache__/LL1Analyzer.cpython-310.pyc,,
|
| 29 |
+
antlr4/__pycache__/Lexer.cpython-310.pyc,,
|
| 30 |
+
antlr4/__pycache__/ListTokenSource.cpython-310.pyc,,
|
| 31 |
+
antlr4/__pycache__/Parser.cpython-310.pyc,,
|
| 32 |
+
antlr4/__pycache__/ParserInterpreter.cpython-310.pyc,,
|
| 33 |
+
antlr4/__pycache__/ParserRuleContext.cpython-310.pyc,,
|
| 34 |
+
antlr4/__pycache__/PredictionContext.cpython-310.pyc,,
|
| 35 |
+
antlr4/__pycache__/Recognizer.cpython-310.pyc,,
|
| 36 |
+
antlr4/__pycache__/RuleContext.cpython-310.pyc,,
|
| 37 |
+
antlr4/__pycache__/StdinStream.cpython-310.pyc,,
|
| 38 |
+
antlr4/__pycache__/Token.cpython-310.pyc,,
|
| 39 |
+
antlr4/__pycache__/TokenStreamRewriter.cpython-310.pyc,,
|
| 40 |
+
antlr4/__pycache__/Utils.cpython-310.pyc,,
|
| 41 |
+
antlr4/__pycache__/__init__.cpython-310.pyc,,
|
| 42 |
+
antlr4/__pycache__/_pygrun.cpython-310.pyc,,
|
| 43 |
+
antlr4/_pygrun.py,sha256=0iyrI1ZYoDznH_IZdtqtazTNuyZSvqLz2D4WBnbVNbI,6289
|
| 44 |
+
antlr4/atn/ATN.py,sha256=LYE8kT-D8FpUd5fpOtyOLqvXLFkUSa83TVFowhCWAiY,5789
|
| 45 |
+
antlr4/atn/ATNConfig.py,sha256=tNdIC6_GrxXllHBx3npAWyDh6KrohLZDV_XyPrydRMY,6565
|
| 46 |
+
antlr4/atn/ATNConfigSet.py,sha256=qRzVsBeMqk2txjG3DrGptwF6Vb2hHC5w3umkSL0GNJw,8312
|
| 47 |
+
antlr4/atn/ATNDeserializationOptions.py,sha256=lUV_bGW6mxj7t20esda5Yv-X9m-U_x1-0xaLifhXIPo,1010
|
| 48 |
+
antlr4/atn/ATNDeserializer.py,sha256=3VDf5ToU5cVwq1j-nCsMhhVQVu2SzrjGfdhZcWriHZ0,18958
|
| 49 |
+
antlr4/atn/ATNSimulator.py,sha256=mDc-G3GF3kSeqpfGDabUOLJ0WLVTqibxZlkvXQYmBRk,2298
|
| 50 |
+
antlr4/atn/ATNState.py,sha256=NbndISWUwFDF_vuBfbTiZZ8GPHoQa6UXdqbD-yjJE7c,7663
|
| 51 |
+
antlr4/atn/ATNType.py,sha256=xgv8AMVU7tc07U73_hRTm1AiZ7MvGhoaP5fTiOrrCGg,422
|
| 52 |
+
antlr4/atn/LexerATNSimulator.py,sha256=kYXRwUvHptSRU8T_K9pSrGlCk9YypWeHlAcjgry1VVo,25465
|
| 53 |
+
antlr4/atn/LexerAction.py,sha256=KUeJwKekBch0m1poSPskHIh-15dcKAG4lR7zlq98tzc,10014
|
| 54 |
+
antlr4/atn/LexerActionExecutor.py,sha256=7rlg17THcwLsuTmh7NsLrTbRH4DTrm8qIdW9_235CEc,6420
|
| 55 |
+
antlr4/atn/ParserATNSimulator.py,sha256=IKCzsDLcznROSVojU-daAygKr3svl0DmK5DhkUllASY,80365
|
| 56 |
+
antlr4/atn/PredictionMode.py,sha256=i8B7MULA7v-qbXeCY_xp6sgi21kHM6kybqIrG6rSrro,22486
|
| 57 |
+
antlr4/atn/SemanticContext.py,sha256=5MB8uOBfsQEIPZMN6yw_meokK_uxUWI6ZjjpT1Agn7E,10561
|
| 58 |
+
antlr4/atn/Transition.py,sha256=ZAsEFpa5I_n-zxD6U-DauM5_33jFK65x3PWu6-NW0RA,8762
|
| 59 |
+
antlr4/atn/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28
|
| 60 |
+
antlr4/atn/__pycache__/ATN.cpython-310.pyc,,
|
| 61 |
+
antlr4/atn/__pycache__/ATNConfig.cpython-310.pyc,,
|
| 62 |
+
antlr4/atn/__pycache__/ATNConfigSet.cpython-310.pyc,,
|
| 63 |
+
antlr4/atn/__pycache__/ATNDeserializationOptions.cpython-310.pyc,,
|
| 64 |
+
antlr4/atn/__pycache__/ATNDeserializer.cpython-310.pyc,,
|
| 65 |
+
antlr4/atn/__pycache__/ATNSimulator.cpython-310.pyc,,
|
| 66 |
+
antlr4/atn/__pycache__/ATNState.cpython-310.pyc,,
|
| 67 |
+
antlr4/atn/__pycache__/ATNType.cpython-310.pyc,,
|
| 68 |
+
antlr4/atn/__pycache__/LexerATNSimulator.cpython-310.pyc,,
|
| 69 |
+
antlr4/atn/__pycache__/LexerAction.cpython-310.pyc,,
|
| 70 |
+
antlr4/atn/__pycache__/LexerActionExecutor.cpython-310.pyc,,
|
| 71 |
+
antlr4/atn/__pycache__/ParserATNSimulator.cpython-310.pyc,,
|
| 72 |
+
antlr4/atn/__pycache__/PredictionMode.cpython-310.pyc,,
|
| 73 |
+
antlr4/atn/__pycache__/SemanticContext.cpython-310.pyc,,
|
| 74 |
+
antlr4/atn/__pycache__/Transition.cpython-310.pyc,,
|
| 75 |
+
antlr4/atn/__pycache__/__init__.cpython-310.pyc,,
|
| 76 |
+
antlr4/dfa/DFA.py,sha256=weIh0uaRfakP12mFvHo7U0tqO3GONV3-nHFkc2xk-ZE,5388
|
| 77 |
+
antlr4/dfa/DFASerializer.py,sha256=1st_HO85yXLYy7gInTEnkztgA6am4CT-yReh-mazp9E,2518
|
| 78 |
+
antlr4/dfa/DFAState.py,sha256=R7JwKf0GtAEs9J_MD_Y0WKcuzdt0BVX1sow-uv9yFYc,5583
|
| 79 |
+
antlr4/dfa/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28
|
| 80 |
+
antlr4/dfa/__pycache__/DFA.cpython-310.pyc,,
|
| 81 |
+
antlr4/dfa/__pycache__/DFASerializer.cpython-310.pyc,,
|
| 82 |
+
antlr4/dfa/__pycache__/DFAState.cpython-310.pyc,,
|
| 83 |
+
antlr4/dfa/__pycache__/__init__.cpython-310.pyc,,
|
| 84 |
+
antlr4/error/DiagnosticErrorListener.py,sha256=EwS2D_Ox6CmvCa16NPJ9ud4QYPHmlPXt6-Wdn1h5Kg8,4430
|
| 85 |
+
antlr4/error/ErrorListener.py,sha256=yP_MDguol4Cj0_pEPyNzeH3v4ZvUjW5iwDjhYTVAHbE,2722
|
| 86 |
+
antlr4/error/ErrorStrategy.py,sha256=0mhzFL57ZVnjKkGrtadta93Zm3NXdF-HW10DVD07VXs,30391
|
| 87 |
+
antlr4/error/Errors.py,sha256=hlKngclBfXdkDiAymhYsvh2OCXlvmHM2kTl_A1vgp-w,6759
|
| 88 |
+
antlr4/error/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28
|
| 89 |
+
antlr4/error/__pycache__/DiagnosticErrorListener.cpython-310.pyc,,
|
| 90 |
+
antlr4/error/__pycache__/ErrorListener.cpython-310.pyc,,
|
| 91 |
+
antlr4/error/__pycache__/ErrorStrategy.cpython-310.pyc,,
|
| 92 |
+
antlr4/error/__pycache__/Errors.cpython-310.pyc,,
|
| 93 |
+
antlr4/error/__pycache__/__init__.cpython-310.pyc,,
|
| 94 |
+
antlr4/tree/Chunk.py,sha256=oCIZjolLq9xkxtVDROEDxfUGgndcEnsDW0eUmLM7Gpk,695
|
| 95 |
+
antlr4/tree/ParseTreeMatch.py,sha256=Dc6GVWSUqoIAFXUaUZqUwCUlZfTcgUbGLGzNf6QxQvE,4485
|
| 96 |
+
antlr4/tree/ParseTreePattern.py,sha256=rGVYxhs9wYLNoR44sjdiNwXROkooJLwoPJAOxn8K4K8,2835
|
| 97 |
+
antlr4/tree/ParseTreePatternMatcher.py,sha256=HtE9yi1Urr2QPLGLJDBvr0lxv6bjuj9CHl-4clahSe8,16388
|
| 98 |
+
antlr4/tree/RuleTagToken.py,sha256=n4zXcmrrfsGyl91pj5ZYcc_CeKMhPrvYkUdppgMBpbY,2022
|
| 99 |
+
antlr4/tree/TokenTagToken.py,sha256=S3o3DJhfzL5kpClxsKyI-Il-xvuuZQiBAIsLCKFjRHo,1576
|
| 100 |
+
antlr4/tree/Tree.py,sha256=ZI7U_5IxBLm_IrnfJOtb12BCPIWyzfeZtLnhHKVVZIw,5572
|
| 101 |
+
antlr4/tree/Trees.py,sha256=JtQ7cYWmKwI9TIBP6y9XIgjlNS4mYjv3ARwOfwWc5Vg,3968
|
| 102 |
+
antlr4/tree/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 103 |
+
antlr4/tree/__pycache__/Chunk.cpython-310.pyc,,
|
| 104 |
+
antlr4/tree/__pycache__/ParseTreeMatch.cpython-310.pyc,,
|
| 105 |
+
antlr4/tree/__pycache__/ParseTreePattern.cpython-310.pyc,,
|
| 106 |
+
antlr4/tree/__pycache__/ParseTreePatternMatcher.cpython-310.pyc,,
|
| 107 |
+
antlr4/tree/__pycache__/RuleTagToken.cpython-310.pyc,,
|
| 108 |
+
antlr4/tree/__pycache__/TokenTagToken.cpython-310.pyc,,
|
| 109 |
+
antlr4/tree/__pycache__/Tree.cpython-310.pyc,,
|
| 110 |
+
antlr4/tree/__pycache__/Trees.cpython-310.pyc,,
|
| 111 |
+
antlr4/tree/__pycache__/__init__.cpython-310.pyc,,
|
| 112 |
+
antlr4/xpath/XPath.py,sha256=qoihVNLvdI5AFi_M3YWoiBFwGO0-x68pCSNOfHgKQbI,9661
|
| 113 |
+
antlr4/xpath/XPathLexer.py,sha256=Dh-4DSobLUERz6iESERcUBtQaUaYVPwi3C74bWZ_Bzs,3446
|
| 114 |
+
antlr4/xpath/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28
|
| 115 |
+
antlr4/xpath/__pycache__/XPath.cpython-310.pyc,,
|
| 116 |
+
antlr4/xpath/__pycache__/XPathLexer.cpython-310.pyc,,
|
| 117 |
+
antlr4/xpath/__pycache__/__init__.cpython-310.pyc,,
|
| 118 |
+
antlr4_python3_runtime-4.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 119 |
+
antlr4_python3_runtime-4.11.0.dist-info/METADATA,sha256=Ndproapb7NxiRP-ltT13tUk85hpHBKt-QKAOO_Q3wzM,291
|
| 120 |
+
antlr4_python3_runtime-4.11.0.dist-info/RECORD,,
|
| 121 |
+
antlr4_python3_runtime-4.11.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
|
| 122 |
+
antlr4_python3_runtime-4.11.0.dist-info/entry_points.txt,sha256=M2tWLwWgEVV1Djr6ugO3b3902YJIpTDHoM8BFMAt4P4,47
|
| 123 |
+
antlr4_python3_runtime-4.11.0.dist-info/top_level.txt,sha256=OsoZsh9bb30wgXb2zBUjdDwYg46MfV-RVZA6Pk8pcB0,7
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.37.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
pygrun = antlr4._pygrun:main
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/antlr4_python3_runtime-4.11.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
antlr4
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/Dockerfile
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Based on: https://github.com/bigcode-project/bigcodebench/blob/main/Docker/Evaluate.Dockerfile
|
| 2 |
+
|
| 3 |
+
FROM public.ecr.aws/lambda/python:3.10
|
| 4 |
+
|
| 5 |
+
ENV PIP_NO_CACHE_DIR=1
|
| 6 |
+
|
| 7 |
+
RUN yum update -y && yum install -y git gcc-c++ python3-tkinter zip unzip procps R libxml2-devel libxslt-devel
|
| 8 |
+
|
| 9 |
+
RUN pip install --upgrade pip
|
| 10 |
+
RUN pip install fastapi gunicorn uvicorn[standard] httpx pydantic==2.* plotly
|
| 11 |
+
|
| 12 |
+
RUN pip install -I --timeout 2000 -r https://github.com/bigcode-project/bigcodebench-annotation/releases/download/v0.1.0/requirements.txt
|
| 13 |
+
|
| 14 |
+
RUN python -m nltk.downloader punkt
|
| 15 |
+
|
| 16 |
+
COPY . .
|
| 17 |
+
|
| 18 |
+
# For matplotlib import caching in reliability guard
|
| 19 |
+
RUN mkdir -p /api/cache/matplotlib
|
| 20 |
+
ENV MPLCONFIGDIR=/api/cache/matplotlib
|
| 21 |
+
|
| 22 |
+
COPY . ${LAMBDA_TASK_ROOT}
|
| 23 |
+
|
| 24 |
+
EXPOSE 8000
|
| 25 |
+
|
| 26 |
+
# Dual-mode startup: Lambda handler OR HTTP server
|
| 27 |
+
CMD ["sh", "-c", "if [ \"$AWS_LAMBDA_RUNTIME_API\" ]; then python -m awslambdaric app.handler; else uvicorn app:app --host 0.0.0.0 --port 8000; fi"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Deploy a lambda verifier for BigCodeBench. Based on [MultiPL-E](../multiple_execution/README.md).
|
| 2 |
+
|
| 3 |
+
### Setup
|
| 4 |
+
|
| 5 |
+
Make sure you have credentials for the S2 account in `~/.aws/credentials`:
|
| 6 |
+
|
| 7 |
+
```sh
|
| 8 |
+
[s2]
|
| 9 |
+
aws_access_key_id=...
|
| 10 |
+
aws_secret_access_key=...
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
### Build and deploy
|
| 14 |
+
|
| 15 |
+
```sh
|
| 16 |
+
# Build + tag docker
|
| 17 |
+
docker buildx build --platform linux/amd64 -t codex/bcb:latest .
|
| 18 |
+
docker tag codex/bcb:latest 896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest
|
| 19 |
+
|
| 20 |
+
# (One time setup) Create ECR registry
|
| 21 |
+
aws ecr create-repository --repository-name codex/bcb --region us-east-1 --profile s2
|
| 22 |
+
|
| 23 |
+
# Push to ECR
|
| 24 |
+
aws ecr get-login-password --region us-east-1 --profile s2 | docker login --username AWS --password-stdin 896129387501.dkr.ecr.us-east-1.amazonaws.com
|
| 25 |
+
docker push 896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest
|
| 26 |
+
|
| 27 |
+
# (One time setup) Create lambda func
|
| 28 |
+
aws lambda create-function \
|
| 29 |
+
--profile s2 \
|
| 30 |
+
--function-name bcb \
|
| 31 |
+
--package-type Image \
|
| 32 |
+
--code ImageUri=896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest \
|
| 33 |
+
--role arn:aws:iam::896129387501:role/lambda-ex \
|
| 34 |
+
--region us-east-1
|
| 35 |
+
|
| 36 |
+
# Deploy to lambda
|
| 37 |
+
aws lambda update-function-code \
|
| 38 |
+
--profile s2 \
|
| 39 |
+
--function-name bcb \
|
| 40 |
+
--image-uri 896129387501.dkr.ecr.us-east-1.amazonaws.com/codex/bcb:latest \
|
| 41 |
+
--region us-east-1
|
| 42 |
+
|
| 43 |
+
# Update and pin the production lambda
|
| 44 |
+
NEW_VERSION=$(aws lambda publish-version \
|
| 45 |
+
--profile s2 \
|
| 46 |
+
--function-name bcb \
|
| 47 |
+
--description "<identifying information for new release>" \
|
| 48 |
+
--region us-east-1 \
|
| 49 |
+
--query 'Version' --output text)
|
| 50 |
+
|
| 51 |
+
# (One time setup) Create lambda alias
|
| 52 |
+
aws lambda create-alias \
|
| 53 |
+
--profile s2 \
|
| 54 |
+
--function-name bcb \
|
| 55 |
+
--name prod \
|
| 56 |
+
--function-version $NEW_VERSION \
|
| 57 |
+
--region us-east-1
|
| 58 |
+
|
| 59 |
+
aws lambda update-alias \
|
| 60 |
+
--profile s2 \
|
| 61 |
+
--function-name bcb \
|
| 62 |
+
--name prod \
|
| 63 |
+
--function-version $NEW_VERSION \
|
| 64 |
+
--region us-east-1
|
| 65 |
+
```
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/__init__.py
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/app.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from fastapi import FastAPI, HTTPException
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
|
| 7 |
+
from execution import untrusted_check
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
app = FastAPI(title="BCB Execution Service", version="1.0.0")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class BCBExecutionRequest(BaseModel):
|
| 14 |
+
solution: str
|
| 15 |
+
test: str
|
| 16 |
+
res_id: str
|
| 17 |
+
task_id: str
|
| 18 |
+
entry_point: str
|
| 19 |
+
calibrate: bool = True
|
| 20 |
+
no_gt: bool = True
|
| 21 |
+
min_time_limit: int = 1
|
| 22 |
+
max_as_limit: int = 30 * 1024
|
| 23 |
+
max_data_limit: int = 30 * 1024
|
| 24 |
+
max_stack_limit: int = 10
|
| 25 |
+
gt_time_limit: int = 20
|
| 26 |
+
code_prompt: Optional[str] = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BCBExecutionResponse(BaseModel):
|
| 30 |
+
task_id: str
|
| 31 |
+
res_id: str
|
| 32 |
+
tested_completion: str
|
| 33 |
+
passed: bool
|
| 34 |
+
exec_result: str
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@app.get("/health")
|
| 38 |
+
async def health_check():
|
| 39 |
+
return {"status": "healthy"}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@app.post("/execute", response_model=BCBExecutionResponse)
|
| 43 |
+
async def execute_code(request: BCBExecutionRequest):
|
| 44 |
+
try:
|
| 45 |
+
solution = request.solution
|
| 46 |
+
|
| 47 |
+
if request.calibrate and request.code_prompt:
|
| 48 |
+
solution = request.code_prompt + "\n pass\n" + solution
|
| 49 |
+
|
| 50 |
+
if not request.no_gt:
|
| 51 |
+
raise HTTPException(
|
| 52 |
+
status_code=501,
|
| 53 |
+
detail="Groundtruth execution is not implemented yet!"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
stat, details = untrusted_check(
|
| 57 |
+
code=solution,
|
| 58 |
+
test_code=request.test,
|
| 59 |
+
entry_point=request.entry_point,
|
| 60 |
+
min_time_limit=request.min_time_limit,
|
| 61 |
+
max_as_limit=request.max_as_limit,
|
| 62 |
+
max_data_limit=request.max_data_limit,
|
| 63 |
+
max_stack_limit=request.max_stack_limit,
|
| 64 |
+
gt_time_limit=request.gt_time_limit,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
passed = stat == "pass"
|
| 68 |
+
|
| 69 |
+
return BCBExecutionResponse(
|
| 70 |
+
task_id=request.task_id,
|
| 71 |
+
res_id=request.res_id,
|
| 72 |
+
tested_completion=solution,
|
| 73 |
+
passed=passed,
|
| 74 |
+
exec_result=json.dumps(details) if details else stat,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# Handler for AWS Lambda
|
| 82 |
+
def handler(event, context):
|
| 83 |
+
request = BCBExecutionRequest(**event)
|
| 84 |
+
response = execute_code(request)
|
| 85 |
+
return json.dumps(response.dict())
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bcb_execution/execution.py
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Based on: https://github.com/bigcode-project/bigcodebench/blob/main/bigcodebench/eval/utils.py
|
| 2 |
+
|
| 3 |
+
# The MIT License
|
| 4 |
+
#
|
| 5 |
+
# Copyright (c) OpenAI (https://openai.com)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 9 |
+
# in the Software without restriction, including without limitation the rights
|
| 10 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 11 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 22 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 23 |
+
# THE SOFTWARE.
|
| 24 |
+
|
| 25 |
+
import contextlib
|
| 26 |
+
import faulthandler
|
| 27 |
+
import io
|
| 28 |
+
import itertools
|
| 29 |
+
import multiprocessing
|
| 30 |
+
import os
|
| 31 |
+
import platform
|
| 32 |
+
import signal
|
| 33 |
+
import subprocess
|
| 34 |
+
import sys
|
| 35 |
+
import tempfile
|
| 36 |
+
import time
|
| 37 |
+
import types
|
| 38 |
+
import unittest
|
| 39 |
+
from multiprocessing import Manager
|
| 40 |
+
from typing import List, Tuple, Union
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
TIMEOUT_LIMIT = 120.0 # BCB default is 240.0
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@contextlib.contextmanager
|
| 48 |
+
def swallow_subprocess_output():
|
| 49 |
+
"""Context manager to swallow stdout and stderr for subprocesses."""
|
| 50 |
+
original_popen = subprocess.Popen
|
| 51 |
+
original_run = subprocess.run
|
| 52 |
+
|
| 53 |
+
def _popen_patch(*args, **kwargs):
|
| 54 |
+
if "capture_output" in kwargs and kwargs["capture_output"]:
|
| 55 |
+
# Avoid setting stdout or stderr if capture_output is True
|
| 56 |
+
kwargs.pop("stdout", None)
|
| 57 |
+
kwargs.pop("stderr", None)
|
| 58 |
+
else:
|
| 59 |
+
kwargs.setdefault("stdout", subprocess.PIPE)
|
| 60 |
+
kwargs.setdefault("stderr", subprocess.PIPE)
|
| 61 |
+
return original_popen(*args, **kwargs)
|
| 62 |
+
|
| 63 |
+
def _run_patch(*args, **kwargs):
|
| 64 |
+
if "capture_output" in kwargs and kwargs["capture_output"]:
|
| 65 |
+
# Avoid setting stdout or stderr if capture_output is True
|
| 66 |
+
kwargs.pop("stdout", None)
|
| 67 |
+
kwargs.pop("stderr", None)
|
| 68 |
+
else:
|
| 69 |
+
kwargs.setdefault("stdout", subprocess.PIPE)
|
| 70 |
+
kwargs.setdefault("stderr", subprocess.PIPE)
|
| 71 |
+
return original_run(*args, **kwargs)
|
| 72 |
+
|
| 73 |
+
subprocess.Popen = _popen_patch
|
| 74 |
+
subprocess.run = _run_patch
|
| 75 |
+
try:
|
| 76 |
+
yield
|
| 77 |
+
finally:
|
| 78 |
+
subprocess.Popen = original_popen
|
| 79 |
+
subprocess.run = original_run
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@contextlib.contextmanager
|
| 83 |
+
def swallow_io():
|
| 84 |
+
stream = WriteOnlyStringIO()
|
| 85 |
+
with contextlib.redirect_stdout(stream):
|
| 86 |
+
with contextlib.redirect_stderr(stream):
|
| 87 |
+
with redirect_stdin(stream):
|
| 88 |
+
with swallow_subprocess_output():
|
| 89 |
+
yield
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@contextlib.contextmanager
|
| 93 |
+
def time_limit(seconds: float):
|
| 94 |
+
def signal_handler(signum, frame):
|
| 95 |
+
raise TimeoutException("Timed out!")
|
| 96 |
+
|
| 97 |
+
signal.setitimer(signal.ITIMER_REAL, seconds)
|
| 98 |
+
signal.signal(signal.SIGALRM, signal_handler)
|
| 99 |
+
try:
|
| 100 |
+
yield
|
| 101 |
+
finally:
|
| 102 |
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@contextlib.contextmanager
|
| 106 |
+
def create_tempdir():
|
| 107 |
+
with tempfile.TemporaryDirectory() as dirname:
|
| 108 |
+
with chdir(dirname):
|
| 109 |
+
yield dirname
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@contextlib.contextmanager
|
| 113 |
+
def chdir(root):
|
| 114 |
+
if root == ".":
|
| 115 |
+
yield
|
| 116 |
+
return
|
| 117 |
+
cwd = os.getcwd()
|
| 118 |
+
os.chdir(root)
|
| 119 |
+
try:
|
| 120 |
+
yield
|
| 121 |
+
except BaseException as exc:
|
| 122 |
+
raise exc
|
| 123 |
+
finally:
|
| 124 |
+
os.chdir(cwd)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@contextlib.contextmanager
|
| 128 |
+
def safe_environment():
|
| 129 |
+
# Save original functions
|
| 130 |
+
original_kill = os.kill
|
| 131 |
+
original_killpg = os.killpg
|
| 132 |
+
original_system = os.system
|
| 133 |
+
original_subprocess_call = subprocess.call
|
| 134 |
+
original_subprocess_check_output = subprocess.check_output
|
| 135 |
+
original_subprocess_run = subprocess.run
|
| 136 |
+
original_subprocess_popen = subprocess.Popen
|
| 137 |
+
original_os_popen = os.popen
|
| 138 |
+
original_os_execv = os.execv
|
| 139 |
+
original_os_execvp = os.execvp
|
| 140 |
+
original_os_execvpe = os.execvpe
|
| 141 |
+
|
| 142 |
+
current_pid = os.getpid()
|
| 143 |
+
current_pgid = os.getpgid(current_pid)
|
| 144 |
+
manager = multiprocessing.Manager()
|
| 145 |
+
child_pids = manager.list()
|
| 146 |
+
|
| 147 |
+
def safe_kill(pid, sig):
|
| 148 |
+
try:
|
| 149 |
+
_ = os.getpgid(pid)
|
| 150 |
+
if pid == current_pid or pid in child_pids:
|
| 151 |
+
original_kill(pid, sig)
|
| 152 |
+
else:
|
| 153 |
+
print(f"Prevented attempt to kill PID {pid} with signal {sig}")
|
| 154 |
+
except ProcessLookupError:
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
def safe_killpg(pgid, sig):
|
| 158 |
+
if pgid == current_pgid or pgid in {os.getpgid(pid) for pid in child_pids}:
|
| 159 |
+
original_killpg(pgid, sig)
|
| 160 |
+
else:
|
| 161 |
+
print(f"Prevented attempt to kill PGID {pgid} with signal {sig}")
|
| 162 |
+
|
| 163 |
+
def safe_system(command):
|
| 164 |
+
print(f"Intercepted system command: {command}")
|
| 165 |
+
if "kill" in command or "killall" in command:
|
| 166 |
+
return 0 # Simulate successful execution without doing anything
|
| 167 |
+
return original_system(command)
|
| 168 |
+
|
| 169 |
+
def safe_subprocess_call(command, *args, **kwargs):
|
| 170 |
+
print(f"Intercepted subprocess call: {command}")
|
| 171 |
+
if "kill" in command or "killall" in command:
|
| 172 |
+
return 0 # Simulate successful execution without doing anything
|
| 173 |
+
return original_subprocess_call(command, *args, **kwargs)
|
| 174 |
+
|
| 175 |
+
def safe_subprocess_check_output(command, *args, **kwargs):
|
| 176 |
+
print(f"Intercepted command: {command}")
|
| 177 |
+
if "ps" in command:
|
| 178 |
+
return b"" # Simulate no processes found
|
| 179 |
+
return original_subprocess_check_output(command, *args, **kwargs)
|
| 180 |
+
|
| 181 |
+
def safe_subprocess_run(*args, **kwargs):
|
| 182 |
+
print(f"Intercepted subprocess run command: {args}")
|
| 183 |
+
if "kill" in args[0] or "killall" in args[0]:
|
| 184 |
+
return subprocess.CompletedProcess(args, 0, b"", b"") # Simulate successful execution
|
| 185 |
+
return original_subprocess_run(*args, **kwargs)
|
| 186 |
+
|
| 187 |
+
class SafePopen(subprocess.Popen):
|
| 188 |
+
def __init__(self, *args, **kwargs):
|
| 189 |
+
print(f"Intercepted Popen command: {args}")
|
| 190 |
+
kwargs["preexec_fn"] = os.setsid # Start the process in a new session
|
| 191 |
+
super().__init__(*args, **kwargs)
|
| 192 |
+
child_pids.append(self.pid)
|
| 193 |
+
|
| 194 |
+
def communicate(self, *args, **kwargs):
|
| 195 |
+
try:
|
| 196 |
+
return super().communicate(*args, **kwargs)
|
| 197 |
+
except subprocess.TimeoutExpired:
|
| 198 |
+
print("Timeout expired, intercepted and returning None")
|
| 199 |
+
return None, None
|
| 200 |
+
|
| 201 |
+
def kill(self):
|
| 202 |
+
print(f"Intercepted kill call for PID {self.pid}")
|
| 203 |
+
safe_kill(self.pid, signal.SIGTERM)
|
| 204 |
+
|
| 205 |
+
def terminate(self):
|
| 206 |
+
print(f"Intercepted terminate call for PID {self.pid}")
|
| 207 |
+
safe_kill(self.pid, signal.SIGTERM)
|
| 208 |
+
|
| 209 |
+
def safe_os_popen(command):
|
| 210 |
+
print(f"Intercepted os.popen command: {command}")
|
| 211 |
+
if "kill" in command or "killall" in command:
|
| 212 |
+
return os.popen("echo Intercepted")
|
| 213 |
+
return original_os_popen(command)
|
| 214 |
+
|
| 215 |
+
def safe_exec(*args, **kwargs):
|
| 216 |
+
print(f"Intercepted exec command: {args}")
|
| 217 |
+
|
| 218 |
+
# Override the risky functions with the safe versions
|
| 219 |
+
os.kill = safe_kill
|
| 220 |
+
os.killpg = safe_killpg
|
| 221 |
+
os.system = safe_system
|
| 222 |
+
subprocess.call = safe_subprocess_call
|
| 223 |
+
subprocess.check_output = safe_subprocess_check_output
|
| 224 |
+
subprocess.run = safe_subprocess_run
|
| 225 |
+
subprocess.Popen = SafePopen
|
| 226 |
+
os.popen = safe_os_popen
|
| 227 |
+
os.execv = safe_exec
|
| 228 |
+
os.execvp = safe_exec
|
| 229 |
+
os.execvpe = safe_exec
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
yield
|
| 233 |
+
finally:
|
| 234 |
+
for pid in child_pids:
|
| 235 |
+
try:
|
| 236 |
+
os.kill(pid, signal.SIGTERM)
|
| 237 |
+
for _ in range(10):
|
| 238 |
+
time.sleep(0.1)
|
| 239 |
+
try:
|
| 240 |
+
os.kill(pid, 0)
|
| 241 |
+
except ProcessLookupError:
|
| 242 |
+
break
|
| 243 |
+
else:
|
| 244 |
+
os.kill(pid, signal.SIGKILL)
|
| 245 |
+
except ProcessLookupError:
|
| 246 |
+
pass
|
| 247 |
+
except Exception as e:
|
| 248 |
+
print(f"Error handling process {pid}: {e}")
|
| 249 |
+
|
| 250 |
+
os.kill = original_kill
|
| 251 |
+
os.killpg = original_killpg
|
| 252 |
+
os.system = original_system
|
| 253 |
+
subprocess.call = original_subprocess_call
|
| 254 |
+
subprocess.check_output = original_subprocess_check_output
|
| 255 |
+
subprocess.run = original_subprocess_run
|
| 256 |
+
subprocess.Popen = original_subprocess_popen
|
| 257 |
+
os.popen = original_os_popen
|
| 258 |
+
os.execv = original_os_execv
|
| 259 |
+
os.execvp = original_os_execvp
|
| 260 |
+
os.execvpe = original_os_execvpe
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class TimeoutException(Exception):
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class WriteOnlyStringIO(io.StringIO):
|
| 268 |
+
"""StringIO that throws an exception when it's read from"""
|
| 269 |
+
|
| 270 |
+
def read(self, *args, **kwargs):
|
| 271 |
+
raise IOError
|
| 272 |
+
|
| 273 |
+
def readline(self, *args, **kwargs):
|
| 274 |
+
raise IOError
|
| 275 |
+
|
| 276 |
+
def readlines(self, *args, **kwargs):
|
| 277 |
+
raise IOError
|
| 278 |
+
|
| 279 |
+
def readable(self, *args, **kwargs):
|
| 280 |
+
"""Returns True if the IO object can be read."""
|
| 281 |
+
return False
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class redirect_stdin(contextlib._RedirectStream): # type: ignore
|
| 285 |
+
_stream = "stdin"
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def reliability_guard(max_as_limit, max_data_limit, max_stack_limit):
|
| 289 |
+
"""
|
| 290 |
+
This disables various destructive functions and prevents the generated code
|
| 291 |
+
from interfering with the test (e.g. fork bomb, killing other processes,
|
| 292 |
+
removing filesystem files, etc.)
|
| 293 |
+
|
| 294 |
+
WARNING
|
| 295 |
+
This function is NOT a security sandbox. Untrusted code, including, model-
|
| 296 |
+
generated code, should not be blindly executed outside of one. See the
|
| 297 |
+
Codex paper for more information about OpenAI's code sandbox, and proceed
|
| 298 |
+
with caution.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
import os
|
| 302 |
+
import time
|
| 303 |
+
|
| 304 |
+
os.environ["TZ"] = "UTC"
|
| 305 |
+
time.tzset()
|
| 306 |
+
|
| 307 |
+
os.environ["OMP_NUM_THREADS"] = "1"
|
| 308 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 309 |
+
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
|
| 310 |
+
|
| 311 |
+
if max_as_limit and max_data_limit and max_stack_limit:
|
| 312 |
+
import resource
|
| 313 |
+
|
| 314 |
+
max_as_limit = max_as_limit * 1024 * 1024
|
| 315 |
+
max_data_limit = max_data_limit * 1024 * 1024
|
| 316 |
+
max_stack_limit = max_stack_limit * 1024 * 1024
|
| 317 |
+
|
| 318 |
+
resource.setrlimit(resource.RLIMIT_AS, (max_as_limit, max_as_limit))
|
| 319 |
+
resource.setrlimit(resource.RLIMIT_DATA, (max_data_limit, max_data_limit))
|
| 320 |
+
if not platform.uname().system == "Darwin":
|
| 321 |
+
resource.setrlimit(resource.RLIMIT_STACK, (max_stack_limit, max_stack_limit))
|
| 322 |
+
|
| 323 |
+
faulthandler.disable()
|
| 324 |
+
|
| 325 |
+
import builtins
|
| 326 |
+
|
| 327 |
+
builtins.exit = None
|
| 328 |
+
builtins.quit = None
|
| 329 |
+
|
| 330 |
+
import matplotlib.pyplot as plt
|
| 331 |
+
|
| 332 |
+
plt.close("all")
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# unbiased estimator from https://github.com/openai/human-eval
|
| 336 |
+
def estimate_pass_at_k(
|
| 337 |
+
num_samples: Union[int, List[int], np.ndarray],
|
| 338 |
+
num_correct: Union[List[int], np.ndarray],
|
| 339 |
+
k: int,
|
| 340 |
+
) -> np.ndarray:
|
| 341 |
+
"""
|
| 342 |
+
Estimates pass@k of each problem and returns them in an array.
|
| 343 |
+
"""
|
| 344 |
+
|
| 345 |
+
def estimator(n: int, c: int, k: int) -> float:
|
| 346 |
+
"""
|
| 347 |
+
Calculates 1 - comb(n - c, k) / comb(n, k).
|
| 348 |
+
"""
|
| 349 |
+
if n - c < k:
|
| 350 |
+
return 1.0
|
| 351 |
+
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
|
| 352 |
+
|
| 353 |
+
if isinstance(num_samples, int):
|
| 354 |
+
num_samples_it = itertools.repeat(num_samples, len(num_correct))
|
| 355 |
+
else:
|
| 356 |
+
assert len(num_samples) == len(num_correct)
|
| 357 |
+
num_samples_it = iter(num_samples)
|
| 358 |
+
|
| 359 |
+
return np.array([estimator(int(n), int(c), k) for n, c in zip(num_samples_it, num_correct)])
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
PASS = "pass"
|
| 363 |
+
FAIL = "fail"
|
| 364 |
+
TIMEOUT = "timeout"
|
| 365 |
+
|
| 366 |
+
_SUCCESS = 0
|
| 367 |
+
_FAILED = 1
|
| 368 |
+
_TIMEOUT = 2
|
| 369 |
+
_UNKNOWN = 3
|
| 370 |
+
|
| 371 |
+
_mapping = {_SUCCESS: PASS, _FAILED: FAIL, _TIMEOUT: TIMEOUT, _UNKNOWN: None}
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def is_floats(x) -> bool:
|
| 375 |
+
# check if it is float; List[float]; Tuple[float]
|
| 376 |
+
if isinstance(x, float):
|
| 377 |
+
return True
|
| 378 |
+
if isinstance(x, (list, tuple)):
|
| 379 |
+
return all(isinstance(i, float) for i in x)
|
| 380 |
+
if isinstance(x, np.ndarray):
|
| 381 |
+
return x.dtype == np.float64 or x.dtype == np.float32
|
| 382 |
+
return False
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def unsafe_execute(
|
| 386 |
+
entry_point: str,
|
| 387 |
+
code: str,
|
| 388 |
+
test_code: str,
|
| 389 |
+
timeout: float,
|
| 390 |
+
max_as_limit: float,
|
| 391 |
+
max_data_limit: float,
|
| 392 |
+
max_stack_limit: float,
|
| 393 |
+
stat, # Value
|
| 394 |
+
details, # Array
|
| 395 |
+
):
|
| 396 |
+
with safe_environment(), create_tempdir():
|
| 397 |
+
# These system calls are needed when cleaning up tempdir.
|
| 398 |
+
import builtins
|
| 399 |
+
import os
|
| 400 |
+
import shutil
|
| 401 |
+
|
| 402 |
+
rmtree = shutil.rmtree
|
| 403 |
+
rmdir = os.rmdir
|
| 404 |
+
chdir = os.chdir
|
| 405 |
+
# Disable functionalities that can make destructive changes to the test.
|
| 406 |
+
reliability_guard(max_as_limit, max_data_limit, max_stack_limit)
|
| 407 |
+
module_name = "__test__"
|
| 408 |
+
new_module = types.ModuleType(module_name)
|
| 409 |
+
# Set necessary attributes for the module
|
| 410 |
+
new_module.__dict__.update(
|
| 411 |
+
{
|
| 412 |
+
"__builtins__": builtins,
|
| 413 |
+
"__file__": f"{module_name}.py",
|
| 414 |
+
"__package__": None,
|
| 415 |
+
"__doc__": None,
|
| 416 |
+
"sys": sys,
|
| 417 |
+
"os": os,
|
| 418 |
+
"environ": os.environ,
|
| 419 |
+
}
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
try:
|
| 423 |
+
full_code = code + "\n" + test_code
|
| 424 |
+
|
| 425 |
+
with swallow_io():
|
| 426 |
+
exec(compile(full_code, f"{module_name}.py", "exec"), new_module.__dict__)
|
| 427 |
+
sys.modules[module_name] = new_module
|
| 428 |
+
TestCases = getattr(new_module, "TestCases")
|
| 429 |
+
loader = unittest.TestLoader()
|
| 430 |
+
suite = loader.loadTestsFromTestCase(TestCases)
|
| 431 |
+
test_result = unittest.TestResult()
|
| 432 |
+
_ = time.time()
|
| 433 |
+
with time_limit(timeout):
|
| 434 |
+
suite.run(test_result)
|
| 435 |
+
|
| 436 |
+
issues = test_result.failures + test_result.errors
|
| 437 |
+
for test, trace in issues:
|
| 438 |
+
details[test.id().split(".")[-1]] = trace
|
| 439 |
+
stat.value = _SUCCESS
|
| 440 |
+
except BaseException as e:
|
| 441 |
+
details["ALL"] = str(e)
|
| 442 |
+
stat.value = _FAILED
|
| 443 |
+
# Needed for cleaning up.
|
| 444 |
+
shutil.rmtree = rmtree
|
| 445 |
+
os.rmdir = rmdir
|
| 446 |
+
os.chdir = chdir
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def untrusted_check(
|
| 450 |
+
code: str,
|
| 451 |
+
test_code: str,
|
| 452 |
+
entry_point: str,
|
| 453 |
+
max_as_limit: float,
|
| 454 |
+
max_data_limit: float,
|
| 455 |
+
max_stack_limit: float,
|
| 456 |
+
min_time_limit: float = 10,
|
| 457 |
+
gt_time_limit: float = 60,
|
| 458 |
+
) -> Tuple[str, np.ndarray]:
|
| 459 |
+
min_time_limit = max(min_time_limit, gt_time_limit)
|
| 460 |
+
timeout = max(os.getenv("BIGCODEBENCH_TIMEOUT_PER_TASK", TIMEOUT_LIMIT), min_time_limit) + 1
|
| 461 |
+
# shared memory objects
|
| 462 |
+
manager = Manager()
|
| 463 |
+
stat = manager.Value("i", 0)
|
| 464 |
+
manager = Manager()
|
| 465 |
+
details = manager.dict()
|
| 466 |
+
|
| 467 |
+
p = multiprocessing.Process(
|
| 468 |
+
target=unsafe_execute,
|
| 469 |
+
args=(
|
| 470 |
+
entry_point,
|
| 471 |
+
code,
|
| 472 |
+
test_code,
|
| 473 |
+
timeout,
|
| 474 |
+
max_as_limit,
|
| 475 |
+
max_data_limit,
|
| 476 |
+
max_stack_limit,
|
| 477 |
+
stat,
|
| 478 |
+
details,
|
| 479 |
+
),
|
| 480 |
+
)
|
| 481 |
+
p.start()
|
| 482 |
+
p.join(timeout=timeout + 1)
|
| 483 |
+
if p.is_alive():
|
| 484 |
+
p.terminate()
|
| 485 |
+
time.sleep(0.1)
|
| 486 |
+
if p.is_alive():
|
| 487 |
+
p.kill()
|
| 488 |
+
time.sleep(0.1)
|
| 489 |
+
|
| 490 |
+
stat = _mapping[stat.value]
|
| 491 |
+
# convert details to a dict
|
| 492 |
+
details = dict(details)
|
| 493 |
+
|
| 494 |
+
if not stat:
|
| 495 |
+
stat = TIMEOUT
|
| 496 |
+
if stat == PASS:
|
| 497 |
+
if details:
|
| 498 |
+
stat = FAIL
|
| 499 |
+
|
| 500 |
+
return stat, details
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def evaluate_files(
|
| 504 |
+
files: List[str],
|
| 505 |
+
inputs: List,
|
| 506 |
+
entry_point: str,
|
| 507 |
+
min_time_limit: float = 0.1,
|
| 508 |
+
gt_time_limit_factor: float = 2.0,
|
| 509 |
+
) -> List[Tuple[str, List[bool]]]:
|
| 510 |
+
ret = []
|
| 511 |
+
# sort files by the id in name (i.e., "../n.py")
|
| 512 |
+
files = sorted(files, key=lambda x: int(x.split("/")[-1].split(".")[0]))
|
| 513 |
+
for file in files:
|
| 514 |
+
code = open(file, "r").read()
|
| 515 |
+
stat, det = untrusted_check(
|
| 516 |
+
code,
|
| 517 |
+
inputs,
|
| 518 |
+
entry_point,
|
| 519 |
+
)
|
| 520 |
+
ret.append((stat, det.tolist()))
|
| 521 |
+
return ret
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .bettermap import *
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/bettermap/bettermap.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 2 |
+
import io
|
| 3 |
+
import sys
|
| 4 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 5 |
+
|
| 6 |
+
import itertools
|
| 7 |
+
import multiprocessing as mp
|
| 8 |
+
from multiprocessing.connection import Connection
|
| 9 |
+
from multiprocessing.context import ForkProcess
|
| 10 |
+
from typing import Iterable, List, Optional, Any, Dict, Tuple
|
| 11 |
+
|
| 12 |
+
import dill
|
| 13 |
+
|
| 14 |
+
from queue import Queue
|
| 15 |
+
from threading import Thread
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
mpctx = mp.get_context("fork")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def threaded_generator(g, maxsize: int = 16):
|
| 22 |
+
q: Queue = Queue(maxsize=maxsize)
|
| 23 |
+
|
| 24 |
+
sentinel = object()
|
| 25 |
+
|
| 26 |
+
def fill_queue():
|
| 27 |
+
try:
|
| 28 |
+
for value in g:
|
| 29 |
+
q.put(value)
|
| 30 |
+
finally:
|
| 31 |
+
q.put(sentinel)
|
| 32 |
+
|
| 33 |
+
thread = Thread(name=repr(g), target=fill_queue, daemon=True)
|
| 34 |
+
thread.start()
|
| 35 |
+
|
| 36 |
+
yield from iter(q.get, sentinel)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def slices(n: int, i: Iterable) -> Iterable[List]:
|
| 40 |
+
i = iter(i)
|
| 41 |
+
while True:
|
| 42 |
+
s = list(itertools.islice(i, n))
|
| 43 |
+
if len(s) > 0:
|
| 44 |
+
yield s
|
| 45 |
+
else:
|
| 46 |
+
break
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def map_per_process(
|
| 50 |
+
fn,
|
| 51 |
+
input_sequence: Iterable,
|
| 52 |
+
*,
|
| 53 |
+
serialization_items: Optional[List[Any]] = None,
|
| 54 |
+
parallelism: int = mpctx.cpu_count()
|
| 55 |
+
) -> Iterable:
|
| 56 |
+
if serialization_items is not None and len(serialization_items) > 0:
|
| 57 |
+
serialization_ids = [id(o) for o in serialization_items]
|
| 58 |
+
class MapPickler(dill.Pickler):
|
| 59 |
+
def persistent_id(self, obj):
|
| 60 |
+
try:
|
| 61 |
+
return serialization_ids.index(id(obj))
|
| 62 |
+
except ValueError:
|
| 63 |
+
return None
|
| 64 |
+
class MapUnpickler(dill.Unpickler):
|
| 65 |
+
def persistent_load(self, pid):
|
| 66 |
+
return serialization_items[pid]
|
| 67 |
+
else:
|
| 68 |
+
MapPickler = dill.Pickler # type: ignore
|
| 69 |
+
MapUnpickler = dill.Unpickler # type: ignore
|
| 70 |
+
def pickle(o: Any) -> bytes:
|
| 71 |
+
with io.BytesIO() as buffer:
|
| 72 |
+
pickler = MapPickler(buffer)
|
| 73 |
+
pickler.dump(o)
|
| 74 |
+
return buffer.getvalue()
|
| 75 |
+
def unpickle(b: bytes) -> Any:
|
| 76 |
+
with io.BytesIO(b) as buffer:
|
| 77 |
+
unpickler = MapUnpickler(buffer)
|
| 78 |
+
return unpickler.load()
|
| 79 |
+
|
| 80 |
+
pipeno_to_pipe: Dict[int, Connection] = {}
|
| 81 |
+
pipeno_to_process: Dict[int, ForkProcess] = {}
|
| 82 |
+
|
| 83 |
+
def process_one_item(send_pipe: Connection, item):
|
| 84 |
+
try:
|
| 85 |
+
processed_item = fn(item)
|
| 86 |
+
except Exception as e:
|
| 87 |
+
import traceback
|
| 88 |
+
send_pipe.send((None, (e, traceback.format_exc())))
|
| 89 |
+
else:
|
| 90 |
+
send_pipe.send((pickle(processed_item), None))
|
| 91 |
+
send_pipe.close()
|
| 92 |
+
|
| 93 |
+
def yield_from_pipes(pipes: List[Connection]):
|
| 94 |
+
for pipe in pipes:
|
| 95 |
+
result, error = pipe.recv()
|
| 96 |
+
pipeno = pipe.fileno()
|
| 97 |
+
del pipeno_to_pipe[pipeno]
|
| 98 |
+
pipe.close()
|
| 99 |
+
|
| 100 |
+
process = pipeno_to_process[pipeno]
|
| 101 |
+
process.join()
|
| 102 |
+
del pipeno_to_process[pipeno]
|
| 103 |
+
|
| 104 |
+
if error is None:
|
| 105 |
+
yield unpickle(result)
|
| 106 |
+
else:
|
| 107 |
+
e, tb = error
|
| 108 |
+
sys.stderr.write("".join(tb))
|
| 109 |
+
raise e
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
for item in input_sequence:
|
| 113 |
+
receive_pipe, send_pipe = mpctx.Pipe(duplex=False)
|
| 114 |
+
process = mpctx.Process(target=process_one_item, args=(send_pipe, item))
|
| 115 |
+
pipeno_to_pipe[receive_pipe.fileno()] = receive_pipe
|
| 116 |
+
pipeno_to_process[receive_pipe.fileno()] = process
|
| 117 |
+
process.start()
|
| 118 |
+
|
| 119 |
+
# read out the values
|
| 120 |
+
timeout = 0 if len(pipeno_to_process) < parallelism else None
|
| 121 |
+
# If we have fewer processes going than we have CPUs, we just pick up the values
|
| 122 |
+
# that are done. If we are at the process limit, we wait until one of them is done.
|
| 123 |
+
ready_pipes = mp.connection.wait(pipeno_to_pipe.values(), timeout=timeout)
|
| 124 |
+
yield from yield_from_pipes(ready_pipes) # type: ignore
|
| 125 |
+
|
| 126 |
+
# yield the rest of the items
|
| 127 |
+
while len(pipeno_to_process) > 0:
|
| 128 |
+
ready_pipes = mp.connection.wait(pipeno_to_pipe.values(), timeout=None)
|
| 129 |
+
yield from yield_from_pipes(ready_pipes) # type: ignore
|
| 130 |
+
|
| 131 |
+
finally:
|
| 132 |
+
for process in pipeno_to_process.values():
|
| 133 |
+
if process.is_alive():
|
| 134 |
+
process.terminate()
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def ordered_map_per_process(
|
| 138 |
+
fn,
|
| 139 |
+
input_sequence: Iterable,
|
| 140 |
+
*,
|
| 141 |
+
serialization_items: Optional[List[Any]] = None
|
| 142 |
+
) -> Iterable:
|
| 143 |
+
def process_item(item):
|
| 144 |
+
index, item = item
|
| 145 |
+
return index, fn(item)
|
| 146 |
+
results_with_index = map_per_process(
|
| 147 |
+
process_item,
|
| 148 |
+
enumerate(input_sequence),
|
| 149 |
+
serialization_items=serialization_items)
|
| 150 |
+
|
| 151 |
+
expected_index = 0
|
| 152 |
+
items_in_wait: List[Tuple[int, Any]] = []
|
| 153 |
+
for item in results_with_index:
|
| 154 |
+
index, result = item
|
| 155 |
+
if index == expected_index:
|
| 156 |
+
yield result
|
| 157 |
+
expected_index = index + 1
|
| 158 |
+
|
| 159 |
+
items_in_wait.sort(reverse=True)
|
| 160 |
+
while len(items_in_wait) > 0 and items_in_wait[-1][0] == expected_index:
|
| 161 |
+
index, result = items_in_wait.pop()
|
| 162 |
+
yield result
|
| 163 |
+
expected_index = index + 1
|
| 164 |
+
else:
|
| 165 |
+
items_in_wait.append(item)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def ordered_map_per_thread(
|
| 169 |
+
fn,
|
| 170 |
+
input_sequence: Iterable,
|
| 171 |
+
*,
|
| 172 |
+
parallelism: int = mpctx.cpu_count()
|
| 173 |
+
) -> Iterable:
|
| 174 |
+
executor = ThreadPoolExecutor(max_workers=parallelism)
|
| 175 |
+
input_sequence = (executor.submit(fn, item) for item in input_sequence)
|
| 176 |
+
input_sequence = threaded_generator(input_sequence, maxsize=parallelism)
|
| 177 |
+
for future in input_sequence:
|
| 178 |
+
yield future.result()
|
| 179 |
+
executor.shutdown()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def map_in_chunks(
|
| 183 |
+
fn,
|
| 184 |
+
input_sequence: Iterable,
|
| 185 |
+
*,
|
| 186 |
+
chunk_size: int = 10,
|
| 187 |
+
serialization_items: Optional[List[Any]] = None
|
| 188 |
+
) -> Iterable:
|
| 189 |
+
def process_chunk(chunk: List) -> List:
|
| 190 |
+
return list(map(fn, chunk))
|
| 191 |
+
|
| 192 |
+
processed_chunks = map_per_process(
|
| 193 |
+
process_chunk,
|
| 194 |
+
slices(chunk_size, input_sequence),
|
| 195 |
+
serialization_items=serialization_items)
|
| 196 |
+
for processed_chunk in processed_chunks:
|
| 197 |
+
yield from processed_chunk
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def ordered_map_in_chunks(
|
| 201 |
+
fn,
|
| 202 |
+
input_sequence: Iterable,
|
| 203 |
+
*,
|
| 204 |
+
chunk_size: int = 10,
|
| 205 |
+
serialization_items: Optional[List[Any]] = None
|
| 206 |
+
) -> Iterable:
|
| 207 |
+
def process_chunk(chunk: List) -> List:
|
| 208 |
+
return list(map(fn, chunk))
|
| 209 |
+
|
| 210 |
+
processed_chunks = ordered_map_per_process(
|
| 211 |
+
process_chunk,
|
| 212 |
+
slices(chunk_size, input_sequence),
|
| 213 |
+
serialization_items=serialization_items)
|
| 214 |
+
for processed_chunk in processed_chunks:
|
| 215 |
+
yield from processed_chunk
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError',
|
| 2 |
+
'FFIError']
|
| 3 |
+
|
| 4 |
+
from .api import FFI
|
| 5 |
+
from .error import CDefError, FFIError, VerificationError, VerificationMissing
|
| 6 |
+
from .error import PkgConfigError
|
| 7 |
+
|
| 8 |
+
__version__ = "2.0.0"
|
| 9 |
+
__version_info__ = (2, 0, 0)
|
| 10 |
+
|
| 11 |
+
# The verifier module file names are based on the CRC32 of a string that
|
| 12 |
+
# contains the following version number. It may be older than __version__
|
| 13 |
+
# if nothing is clearly incompatible.
|
| 14 |
+
__version_verifier_modules__ = "0.8.6"
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_errors.h
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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and display them in a background thread
|
| 13 |
+
with MessageBox. The idea is that if the whole program closes
|
| 14 |
+
as a result of this problem, then likely it is already a console
|
| 15 |
+
program and you can read the stderr output in the console too.
|
| 16 |
+
If it is not a console program, then it will likely show its own
|
| 17 |
+
dialog to complain, or generally not abruptly close, and for this
|
| 18 |
+
case the background thread should stay alive.
|
| 19 |
+
*/
|
| 20 |
+
static void *volatile _cffi_bootstrap_text;
|
| 21 |
+
|
| 22 |
+
static PyObject *_cffi_start_error_capture(void)
|
| 23 |
+
{
|
| 24 |
+
PyObject *result = NULL;
|
| 25 |
+
PyObject *x, *m, *bi;
|
| 26 |
+
|
| 27 |
+
if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text,
|
| 28 |
+
(void *)1, NULL) != NULL)
|
| 29 |
+
return (PyObject *)1;
|
| 30 |
+
|
| 31 |
+
m = PyImport_AddModule("_cffi_error_capture");
|
| 32 |
+
if (m == NULL)
|
| 33 |
+
goto error;
|
| 34 |
+
|
| 35 |
+
result = PyModule_GetDict(m);
|
| 36 |
+
if (result == NULL)
|
| 37 |
+
goto error;
|
| 38 |
+
|
| 39 |
+
#if PY_MAJOR_VERSION >= 3
|
| 40 |
+
bi = PyImport_ImportModule("builtins");
|
| 41 |
+
#else
|
| 42 |
+
bi = PyImport_ImportModule("__builtin__");
|
| 43 |
+
#endif
|
| 44 |
+
if (bi == NULL)
|
| 45 |
+
goto error;
|
| 46 |
+
PyDict_SetItemString(result, "__builtins__", bi);
|
| 47 |
+
Py_DECREF(bi);
|
| 48 |
+
|
| 49 |
+
x = PyRun_String(
|
| 50 |
+
"import sys\n"
|
| 51 |
+
"class FileLike:\n"
|
| 52 |
+
" def write(self, x):\n"
|
| 53 |
+
" try:\n"
|
| 54 |
+
" of.write(x)\n"
|
| 55 |
+
" except: pass\n"
|
| 56 |
+
" self.buf += x\n"
|
| 57 |
+
" def flush(self):\n"
|
| 58 |
+
" pass\n"
|
| 59 |
+
"fl = FileLike()\n"
|
| 60 |
+
"fl.buf = ''\n"
|
| 61 |
+
"of = sys.stderr\n"
|
| 62 |
+
"sys.stderr = fl\n"
|
| 63 |
+
"def done():\n"
|
| 64 |
+
" sys.stderr = of\n"
|
| 65 |
+
" return fl.buf\n", /* make sure the returned value stays alive */
|
| 66 |
+
Py_file_input,
|
| 67 |
+
result, result);
|
| 68 |
+
Py_XDECREF(x);
|
| 69 |
+
|
| 70 |
+
error:
|
| 71 |
+
if (PyErr_Occurred())
|
| 72 |
+
{
|
| 73 |
+
PyErr_WriteUnraisable(Py_None);
|
| 74 |
+
PyErr_Clear();
|
| 75 |
+
}
|
| 76 |
+
return result;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
#pragma comment(lib, "user32.lib")
|
| 80 |
+
|
| 81 |
+
static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)
|
| 82 |
+
{
|
| 83 |
+
Sleep(666); /* may be interrupted if the whole process is closing */
|
| 84 |
+
#if PY_MAJOR_VERSION >= 3
|
| 85 |
+
MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text,
|
| 86 |
+
L"Python-CFFI error",
|
| 87 |
+
MB_OK | MB_ICONERROR);
|
| 88 |
+
#else
|
| 89 |
+
MessageBoxA(NULL, (char *)_cffi_bootstrap_text,
|
| 90 |
+
"Python-CFFI error",
|
| 91 |
+
MB_OK | MB_ICONERROR);
|
| 92 |
+
#endif
|
| 93 |
+
_cffi_bootstrap_text = NULL;
|
| 94 |
+
return 0;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
static void _cffi_stop_error_capture(PyObject *ecap)
|
| 98 |
+
{
|
| 99 |
+
PyObject *s;
|
| 100 |
+
void *text;
|
| 101 |
+
|
| 102 |
+
if (ecap == (PyObject *)1)
|
| 103 |
+
return;
|
| 104 |
+
|
| 105 |
+
if (ecap == NULL)
|
| 106 |
+
goto error;
|
| 107 |
+
|
| 108 |
+
s = PyRun_String("done()", Py_eval_input, ecap, ecap);
|
| 109 |
+
if (s == NULL)
|
| 110 |
+
goto error;
|
| 111 |
+
|
| 112 |
+
/* Show a dialog box, but in a background thread, and
|
| 113 |
+
never show multiple dialog boxes at once. */
|
| 114 |
+
#if PY_MAJOR_VERSION >= 3
|
| 115 |
+
text = PyUnicode_AsWideCharString(s, NULL);
|
| 116 |
+
#else
|
| 117 |
+
text = PyString_AsString(s);
|
| 118 |
+
#endif
|
| 119 |
+
|
| 120 |
+
_cffi_bootstrap_text = text;
|
| 121 |
+
|
| 122 |
+
if (text != NULL)
|
| 123 |
+
{
|
| 124 |
+
HANDLE h;
|
| 125 |
+
h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,
|
| 126 |
+
NULL, 0, NULL);
|
| 127 |
+
if (h != NULL)
|
| 128 |
+
CloseHandle(h);
|
| 129 |
+
}
|
| 130 |
+
/* decref the string, but it should stay alive as 'fl.buf'
|
| 131 |
+
in the small module above. It will really be freed only if
|
| 132 |
+
we later get another similar error. So it's a leak of at
|
| 133 |
+
most one copy of the small module. That's fine for this
|
| 134 |
+
situation which is usually a "fatal error" anyway. */
|
| 135 |
+
Py_DECREF(s);
|
| 136 |
+
PyErr_Clear();
|
| 137 |
+
return;
|
| 138 |
+
|
| 139 |
+
error:
|
| 140 |
+
_cffi_bootstrap_text = NULL;
|
| 141 |
+
PyErr_Clear();
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
#else
|
| 145 |
+
|
| 146 |
+
static PyObject *_cffi_start_error_capture(void) { return NULL; }
|
| 147 |
+
static void _cffi_stop_error_capture(PyObject *ecap) { }
|
| 148 |
+
|
| 149 |
+
#endif
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_cffi_include.h
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#define _CFFI_
|
| 2 |
+
|
| 3 |
+
/* We try to define Py_LIMITED_API before including Python.h.
|
| 4 |
+
|
| 5 |
+
Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and
|
| 6 |
+
Py_REF_DEBUG are not defined. This is a best-effort approximation:
|
| 7 |
+
we can learn about Py_DEBUG from pyconfig.h, but it is unclear if
|
| 8 |
+
the same works for the other two macros. Py_DEBUG implies them,
|
| 9 |
+
but not the other way around.
|
| 10 |
+
|
| 11 |
+
The implementation is messy (issue #350): on Windows, with _MSC_VER,
|
| 12 |
+
we have to define Py_LIMITED_API even before including pyconfig.h.
|
| 13 |
+
In that case, we guess what pyconfig.h will do to the macros above,
|
| 14 |
+
and check our guess after the #include.
|
| 15 |
+
|
| 16 |
+
Note that on Windows, with CPython 3.x, you need >= 3.5 and virtualenv
|
| 17 |
+
version >= 16.0.0. With older versions of either, you don't get a
|
| 18 |
+
copy of PYTHON3.DLL in the virtualenv. We can't check the version of
|
| 19 |
+
CPython *before* we even include pyconfig.h. ffi.set_source() puts
|
| 20 |
+
a ``#define _CFFI_NO_LIMITED_API'' at the start of this file if it is
|
| 21 |
+
running on Windows < 3.5, as an attempt at fixing it, but that's
|
| 22 |
+
arguably wrong because it may not be the target version of Python.
|
| 23 |
+
Still better than nothing I guess. As another workaround, you can
|
| 24 |
+
remove the definition of Py_LIMITED_API here.
|
| 25 |
+
|
| 26 |
+
See also 'py_limited_api' in cffi/setuptools_ext.py.
|
| 27 |
+
*/
|
| 28 |
+
#if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API)
|
| 29 |
+
# ifdef _MSC_VER
|
| 30 |
+
# if !defined(_DEBUG) && !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API)
|
| 31 |
+
# define Py_LIMITED_API
|
| 32 |
+
# endif
|
| 33 |
+
# include <pyconfig.h>
|
| 34 |
+
/* sanity-check: Py_LIMITED_API will cause crashes if any of these
|
| 35 |
+
are also defined. Normally, the Python file PC/pyconfig.h does not
|
| 36 |
+
cause any of these to be defined, with the exception that _DEBUG
|
| 37 |
+
causes Py_DEBUG. Double-check that. */
|
| 38 |
+
# ifdef Py_LIMITED_API
|
| 39 |
+
# if defined(Py_DEBUG)
|
| 40 |
+
# error "pyconfig.h unexpectedly defines Py_DEBUG, but Py_LIMITED_API is set"
|
| 41 |
+
# endif
|
| 42 |
+
# if defined(Py_TRACE_REFS)
|
| 43 |
+
# error "pyconfig.h unexpectedly defines Py_TRACE_REFS, but Py_LIMITED_API is set"
|
| 44 |
+
# endif
|
| 45 |
+
# if defined(Py_REF_DEBUG)
|
| 46 |
+
# error "pyconfig.h unexpectedly defines Py_REF_DEBUG, but Py_LIMITED_API is set"
|
| 47 |
+
# endif
|
| 48 |
+
# endif
|
| 49 |
+
# else
|
| 50 |
+
# include <pyconfig.h>
|
| 51 |
+
# if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API)
|
| 52 |
+
# define Py_LIMITED_API
|
| 53 |
+
# endif
|
| 54 |
+
# endif
|
| 55 |
+
#endif
|
| 56 |
+
|
| 57 |
+
#include <Python.h>
|
| 58 |
+
#ifdef __cplusplus
|
| 59 |
+
extern "C" {
|
| 60 |
+
#endif
|
| 61 |
+
#include <stddef.h>
|
| 62 |
+
#include "parse_c_type.h"
|
| 63 |
+
|
| 64 |
+
/* this block of #ifs should be kept exactly identical between
|
| 65 |
+
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
|
| 66 |
+
and cffi/_cffi_include.h */
|
| 67 |
+
#if defined(_MSC_VER)
|
| 68 |
+
# include <malloc.h> /* for alloca() */
|
| 69 |
+
# if _MSC_VER < 1600 /* MSVC < 2010 */
|
| 70 |
+
typedef __int8 int8_t;
|
| 71 |
+
typedef __int16 int16_t;
|
| 72 |
+
typedef __int32 int32_t;
|
| 73 |
+
typedef __int64 int64_t;
|
| 74 |
+
typedef unsigned __int8 uint8_t;
|
| 75 |
+
typedef unsigned __int16 uint16_t;
|
| 76 |
+
typedef unsigned __int32 uint32_t;
|
| 77 |
+
typedef unsigned __int64 uint64_t;
|
| 78 |
+
typedef __int8 int_least8_t;
|
| 79 |
+
typedef __int16 int_least16_t;
|
| 80 |
+
typedef __int32 int_least32_t;
|
| 81 |
+
typedef __int64 int_least64_t;
|
| 82 |
+
typedef unsigned __int8 uint_least8_t;
|
| 83 |
+
typedef unsigned __int16 uint_least16_t;
|
| 84 |
+
typedef unsigned __int32 uint_least32_t;
|
| 85 |
+
typedef unsigned __int64 uint_least64_t;
|
| 86 |
+
typedef __int8 int_fast8_t;
|
| 87 |
+
typedef __int16 int_fast16_t;
|
| 88 |
+
typedef __int32 int_fast32_t;
|
| 89 |
+
typedef __int64 int_fast64_t;
|
| 90 |
+
typedef unsigned __int8 uint_fast8_t;
|
| 91 |
+
typedef unsigned __int16 uint_fast16_t;
|
| 92 |
+
typedef unsigned __int32 uint_fast32_t;
|
| 93 |
+
typedef unsigned __int64 uint_fast64_t;
|
| 94 |
+
typedef __int64 intmax_t;
|
| 95 |
+
typedef unsigned __int64 uintmax_t;
|
| 96 |
+
# else
|
| 97 |
+
# include <stdint.h>
|
| 98 |
+
# endif
|
| 99 |
+
# if _MSC_VER < 1800 /* MSVC < 2013 */
|
| 100 |
+
# ifndef __cplusplus
|
| 101 |
+
typedef unsigned char _Bool;
|
| 102 |
+
# endif
|
| 103 |
+
# endif
|
| 104 |
+
# define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */
|
| 105 |
+
# define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */
|
| 106 |
+
#else
|
| 107 |
+
# include <stdint.h>
|
| 108 |
+
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
|
| 109 |
+
# include <alloca.h>
|
| 110 |
+
# endif
|
| 111 |
+
# define _cffi_float_complex_t float _Complex
|
| 112 |
+
# define _cffi_double_complex_t double _Complex
|
| 113 |
+
#endif
|
| 114 |
+
|
| 115 |
+
#ifdef __GNUC__
|
| 116 |
+
# define _CFFI_UNUSED_FN __attribute__((unused))
|
| 117 |
+
#else
|
| 118 |
+
# define _CFFI_UNUSED_FN /* nothing */
|
| 119 |
+
#endif
|
| 120 |
+
|
| 121 |
+
#ifdef __cplusplus
|
| 122 |
+
# ifndef _Bool
|
| 123 |
+
typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */
|
| 124 |
+
# endif
|
| 125 |
+
#endif
|
| 126 |
+
|
| 127 |
+
/********** CPython-specific section **********/
|
| 128 |
+
#ifndef PYPY_VERSION
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
#if PY_MAJOR_VERSION >= 3
|
| 132 |
+
# define PyInt_FromLong PyLong_FromLong
|
| 133 |
+
#endif
|
| 134 |
+
|
| 135 |
+
#define _cffi_from_c_double PyFloat_FromDouble
|
| 136 |
+
#define _cffi_from_c_float PyFloat_FromDouble
|
| 137 |
+
#define _cffi_from_c_long PyInt_FromLong
|
| 138 |
+
#define _cffi_from_c_ulong PyLong_FromUnsignedLong
|
| 139 |
+
#define _cffi_from_c_longlong PyLong_FromLongLong
|
| 140 |
+
#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong
|
| 141 |
+
#define _cffi_from_c__Bool PyBool_FromLong
|
| 142 |
+
|
| 143 |
+
#define _cffi_to_c_double PyFloat_AsDouble
|
| 144 |
+
#define _cffi_to_c_float PyFloat_AsDouble
|
| 145 |
+
|
| 146 |
+
#define _cffi_from_c_int(x, type) \
|
| 147 |
+
(((type)-1) > 0 ? /* unsigned */ \
|
| 148 |
+
(sizeof(type) < sizeof(long) ? \
|
| 149 |
+
PyInt_FromLong((long)x) : \
|
| 150 |
+
sizeof(type) == sizeof(long) ? \
|
| 151 |
+
PyLong_FromUnsignedLong((unsigned long)x) : \
|
| 152 |
+
PyLong_FromUnsignedLongLong((unsigned long long)x)) : \
|
| 153 |
+
(sizeof(type) <= sizeof(long) ? \
|
| 154 |
+
PyInt_FromLong((long)x) : \
|
| 155 |
+
PyLong_FromLongLong((long long)x)))
|
| 156 |
+
|
| 157 |
+
#define _cffi_to_c_int(o, type) \
|
| 158 |
+
((type)( \
|
| 159 |
+
sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
|
| 160 |
+
: (type)_cffi_to_c_i8(o)) : \
|
| 161 |
+
sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
|
| 162 |
+
: (type)_cffi_to_c_i16(o)) : \
|
| 163 |
+
sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
|
| 164 |
+
: (type)_cffi_to_c_i32(o)) : \
|
| 165 |
+
sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
|
| 166 |
+
: (type)_cffi_to_c_i64(o)) : \
|
| 167 |
+
(Py_FatalError("unsupported size for type " #type), (type)0)))
|
| 168 |
+
|
| 169 |
+
#define _cffi_to_c_i8 \
|
| 170 |
+
((int(*)(PyObject *))_cffi_exports[1])
|
| 171 |
+
#define _cffi_to_c_u8 \
|
| 172 |
+
((int(*)(PyObject *))_cffi_exports[2])
|
| 173 |
+
#define _cffi_to_c_i16 \
|
| 174 |
+
((int(*)(PyObject *))_cffi_exports[3])
|
| 175 |
+
#define _cffi_to_c_u16 \
|
| 176 |
+
((int(*)(PyObject *))_cffi_exports[4])
|
| 177 |
+
#define _cffi_to_c_i32 \
|
| 178 |
+
((int(*)(PyObject *))_cffi_exports[5])
|
| 179 |
+
#define _cffi_to_c_u32 \
|
| 180 |
+
((unsigned int(*)(PyObject *))_cffi_exports[6])
|
| 181 |
+
#define _cffi_to_c_i64 \
|
| 182 |
+
((long long(*)(PyObject *))_cffi_exports[7])
|
| 183 |
+
#define _cffi_to_c_u64 \
|
| 184 |
+
((unsigned long long(*)(PyObject *))_cffi_exports[8])
|
| 185 |
+
#define _cffi_to_c_char \
|
| 186 |
+
((int(*)(PyObject *))_cffi_exports[9])
|
| 187 |
+
#define _cffi_from_c_pointer \
|
| 188 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10])
|
| 189 |
+
#define _cffi_to_c_pointer \
|
| 190 |
+
((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11])
|
| 191 |
+
#define _cffi_get_struct_layout \
|
| 192 |
+
not used any more
|
| 193 |
+
#define _cffi_restore_errno \
|
| 194 |
+
((void(*)(void))_cffi_exports[13])
|
| 195 |
+
#define _cffi_save_errno \
|
| 196 |
+
((void(*)(void))_cffi_exports[14])
|
| 197 |
+
#define _cffi_from_c_char \
|
| 198 |
+
((PyObject *(*)(char))_cffi_exports[15])
|
| 199 |
+
#define _cffi_from_c_deref \
|
| 200 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16])
|
| 201 |
+
#define _cffi_to_c \
|
| 202 |
+
((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17])
|
| 203 |
+
#define _cffi_from_c_struct \
|
| 204 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18])
|
| 205 |
+
#define _cffi_to_c_wchar_t \
|
| 206 |
+
((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19])
|
| 207 |
+
#define _cffi_from_c_wchar_t \
|
| 208 |
+
((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20])
|
| 209 |
+
#define _cffi_to_c_long_double \
|
| 210 |
+
((long double(*)(PyObject *))_cffi_exports[21])
|
| 211 |
+
#define _cffi_to_c__Bool \
|
| 212 |
+
((_Bool(*)(PyObject *))_cffi_exports[22])
|
| 213 |
+
#define _cffi_prepare_pointer_call_argument \
|
| 214 |
+
((Py_ssize_t(*)(struct _cffi_ctypedescr *, \
|
| 215 |
+
PyObject *, char **))_cffi_exports[23])
|
| 216 |
+
#define _cffi_convert_array_from_object \
|
| 217 |
+
((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24])
|
| 218 |
+
#define _CFFI_CPIDX 25
|
| 219 |
+
#define _cffi_call_python \
|
| 220 |
+
((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX])
|
| 221 |
+
#define _cffi_to_c_wchar3216_t \
|
| 222 |
+
((int(*)(PyObject *))_cffi_exports[26])
|
| 223 |
+
#define _cffi_from_c_wchar3216_t \
|
| 224 |
+
((PyObject *(*)(int))_cffi_exports[27])
|
| 225 |
+
#define _CFFI_NUM_EXPORTS 28
|
| 226 |
+
|
| 227 |
+
struct _cffi_ctypedescr;
|
| 228 |
+
|
| 229 |
+
static void *_cffi_exports[_CFFI_NUM_EXPORTS];
|
| 230 |
+
|
| 231 |
+
#define _cffi_type(index) ( \
|
| 232 |
+
assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \
|
| 233 |
+
(struct _cffi_ctypedescr *)_cffi_types[index])
|
| 234 |
+
|
| 235 |
+
static PyObject *_cffi_init(const char *module_name, Py_ssize_t version,
|
| 236 |
+
const struct _cffi_type_context_s *ctx)
|
| 237 |
+
{
|
| 238 |
+
PyObject *module, *o_arg, *new_module;
|
| 239 |
+
void *raw[] = {
|
| 240 |
+
(void *)module_name,
|
| 241 |
+
(void *)version,
|
| 242 |
+
(void *)_cffi_exports,
|
| 243 |
+
(void *)ctx,
|
| 244 |
+
};
|
| 245 |
+
|
| 246 |
+
module = PyImport_ImportModule("_cffi_backend");
|
| 247 |
+
if (module == NULL)
|
| 248 |
+
goto failure;
|
| 249 |
+
|
| 250 |
+
o_arg = PyLong_FromVoidPtr((void *)raw);
|
| 251 |
+
if (o_arg == NULL)
|
| 252 |
+
goto failure;
|
| 253 |
+
|
| 254 |
+
new_module = PyObject_CallMethod(
|
| 255 |
+
module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg);
|
| 256 |
+
|
| 257 |
+
Py_DECREF(o_arg);
|
| 258 |
+
Py_DECREF(module);
|
| 259 |
+
return new_module;
|
| 260 |
+
|
| 261 |
+
failure:
|
| 262 |
+
Py_XDECREF(module);
|
| 263 |
+
return NULL;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
#ifdef HAVE_WCHAR_H
|
| 268 |
+
typedef wchar_t _cffi_wchar_t;
|
| 269 |
+
#else
|
| 270 |
+
typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */
|
| 271 |
+
#endif
|
| 272 |
+
|
| 273 |
+
_CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o)
|
| 274 |
+
{
|
| 275 |
+
if (sizeof(_cffi_wchar_t) == 2)
|
| 276 |
+
return (uint16_t)_cffi_to_c_wchar_t(o);
|
| 277 |
+
else
|
| 278 |
+
return (uint16_t)_cffi_to_c_wchar3216_t(o);
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x)
|
| 282 |
+
{
|
| 283 |
+
if (sizeof(_cffi_wchar_t) == 2)
|
| 284 |
+
return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
|
| 285 |
+
else
|
| 286 |
+
return _cffi_from_c_wchar3216_t((int)x);
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
_CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o)
|
| 290 |
+
{
|
| 291 |
+
if (sizeof(_cffi_wchar_t) == 4)
|
| 292 |
+
return (int)_cffi_to_c_wchar_t(o);
|
| 293 |
+
else
|
| 294 |
+
return (int)_cffi_to_c_wchar3216_t(o);
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(unsigned int x)
|
| 298 |
+
{
|
| 299 |
+
if (sizeof(_cffi_wchar_t) == 4)
|
| 300 |
+
return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
|
| 301 |
+
else
|
| 302 |
+
return _cffi_from_c_wchar3216_t((int)x);
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
union _cffi_union_alignment_u {
|
| 306 |
+
unsigned char m_char;
|
| 307 |
+
unsigned short m_short;
|
| 308 |
+
unsigned int m_int;
|
| 309 |
+
unsigned long m_long;
|
| 310 |
+
unsigned long long m_longlong;
|
| 311 |
+
float m_float;
|
| 312 |
+
double m_double;
|
| 313 |
+
long double m_longdouble;
|
| 314 |
+
};
|
| 315 |
+
|
| 316 |
+
struct _cffi_freeme_s {
|
| 317 |
+
struct _cffi_freeme_s *next;
|
| 318 |
+
union _cffi_union_alignment_u alignment;
|
| 319 |
+
};
|
| 320 |
+
|
| 321 |
+
_CFFI_UNUSED_FN static int
|
| 322 |
+
_cffi_convert_array_argument(struct _cffi_ctypedescr *ctptr, PyObject *arg,
|
| 323 |
+
char **output_data, Py_ssize_t datasize,
|
| 324 |
+
struct _cffi_freeme_s **freeme)
|
| 325 |
+
{
|
| 326 |
+
char *p;
|
| 327 |
+
if (datasize < 0)
|
| 328 |
+
return -1;
|
| 329 |
+
|
| 330 |
+
p = *output_data;
|
| 331 |
+
if (p == NULL) {
|
| 332 |
+
struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc(
|
| 333 |
+
offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize);
|
| 334 |
+
if (fp == NULL)
|
| 335 |
+
return -1;
|
| 336 |
+
fp->next = *freeme;
|
| 337 |
+
*freeme = fp;
|
| 338 |
+
p = *output_data = (char *)&fp->alignment;
|
| 339 |
+
}
|
| 340 |
+
memset((void *)p, 0, (size_t)datasize);
|
| 341 |
+
return _cffi_convert_array_from_object(p, ctptr, arg);
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
_CFFI_UNUSED_FN static void
|
| 345 |
+
_cffi_free_array_arguments(struct _cffi_freeme_s *freeme)
|
| 346 |
+
{
|
| 347 |
+
do {
|
| 348 |
+
void *p = (void *)freeme;
|
| 349 |
+
freeme = freeme->next;
|
| 350 |
+
PyObject_Free(p);
|
| 351 |
+
} while (freeme != NULL);
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
/********** end CPython-specific section **********/
|
| 355 |
+
#else
|
| 356 |
+
_CFFI_UNUSED_FN
|
| 357 |
+
static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *);
|
| 358 |
+
# define _cffi_call_python _cffi_call_python_org
|
| 359 |
+
#endif
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
#define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0]))
|
| 363 |
+
|
| 364 |
+
#define _cffi_prim_int(size, sign) \
|
| 365 |
+
((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \
|
| 366 |
+
(size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \
|
| 367 |
+
(size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \
|
| 368 |
+
(size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \
|
| 369 |
+
_CFFI__UNKNOWN_PRIM)
|
| 370 |
+
|
| 371 |
+
#define _cffi_prim_float(size) \
|
| 372 |
+
((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \
|
| 373 |
+
(size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \
|
| 374 |
+
(size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \
|
| 375 |
+
_CFFI__UNKNOWN_FLOAT_PRIM)
|
| 376 |
+
|
| 377 |
+
#define _cffi_check_int(got, got_nonpos, expected) \
|
| 378 |
+
((got_nonpos) == (expected <= 0) && \
|
| 379 |
+
(got) == (unsigned long long)expected)
|
| 380 |
+
|
| 381 |
+
#ifdef MS_WIN32
|
| 382 |
+
# define _cffi_stdcall __stdcall
|
| 383 |
+
#else
|
| 384 |
+
# define _cffi_stdcall /* nothing */
|
| 385 |
+
#endif
|
| 386 |
+
|
| 387 |
+
#ifdef __cplusplus
|
| 388 |
+
}
|
| 389 |
+
#endif
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_embedding.h
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
/***** Support code for embedding *****/
|
| 3 |
+
|
| 4 |
+
#ifdef __cplusplus
|
| 5 |
+
extern "C" {
|
| 6 |
+
#endif
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
#if defined(_WIN32)
|
| 10 |
+
# define CFFI_DLLEXPORT __declspec(dllexport)
|
| 11 |
+
#elif defined(__GNUC__)
|
| 12 |
+
# define CFFI_DLLEXPORT __attribute__((visibility("default")))
|
| 13 |
+
#else
|
| 14 |
+
# define CFFI_DLLEXPORT /* nothing */
|
| 15 |
+
#endif
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
/* There are two global variables of type _cffi_call_python_fnptr:
|
| 19 |
+
|
| 20 |
+
* _cffi_call_python, which we declare just below, is the one called
|
| 21 |
+
by ``extern "Python"`` implementations.
|
| 22 |
+
|
| 23 |
+
* _cffi_call_python_org, which on CPython is actually part of the
|
| 24 |
+
_cffi_exports[] array, is the function pointer copied from
|
| 25 |
+
_cffi_backend. If _cffi_start_python() fails, then this is set
|
| 26 |
+
to NULL; otherwise, it should never be NULL.
|
| 27 |
+
|
| 28 |
+
After initialization is complete, both are equal. However, the
|
| 29 |
+
first one remains equal to &_cffi_start_and_call_python until the
|
| 30 |
+
very end of initialization, when we are (or should be) sure that
|
| 31 |
+
concurrent threads also see a completely initialized world, and
|
| 32 |
+
only then is it changed.
|
| 33 |
+
*/
|
| 34 |
+
#undef _cffi_call_python
|
| 35 |
+
typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *);
|
| 36 |
+
static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *);
|
| 37 |
+
static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python;
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
#ifndef _MSC_VER
|
| 41 |
+
/* --- Assuming a GCC not infinitely old --- */
|
| 42 |
+
# define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n)
|
| 43 |
+
# define cffi_write_barrier() __sync_synchronize()
|
| 44 |
+
# if !defined(__amd64__) && !defined(__x86_64__) && \
|
| 45 |
+
!defined(__i386__) && !defined(__i386)
|
| 46 |
+
# define cffi_read_barrier() __sync_synchronize()
|
| 47 |
+
# else
|
| 48 |
+
# define cffi_read_barrier() (void)0
|
| 49 |
+
# endif
|
| 50 |
+
#else
|
| 51 |
+
/* --- Windows threads version --- */
|
| 52 |
+
# include <Windows.h>
|
| 53 |
+
# define cffi_compare_and_swap(l,o,n) \
|
| 54 |
+
(InterlockedCompareExchangePointer(l,n,o) == (o))
|
| 55 |
+
# define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0)
|
| 56 |
+
# define cffi_read_barrier() (void)0
|
| 57 |
+
static volatile LONG _cffi_dummy;
|
| 58 |
+
#endif
|
| 59 |
+
|
| 60 |
+
#ifdef WITH_THREAD
|
| 61 |
+
# ifndef _MSC_VER
|
| 62 |
+
# include <pthread.h>
|
| 63 |
+
static pthread_mutex_t _cffi_embed_startup_lock;
|
| 64 |
+
# else
|
| 65 |
+
static CRITICAL_SECTION _cffi_embed_startup_lock;
|
| 66 |
+
# endif
|
| 67 |
+
static char _cffi_embed_startup_lock_ready = 0;
|
| 68 |
+
#endif
|
| 69 |
+
|
| 70 |
+
static void _cffi_acquire_reentrant_mutex(void)
|
| 71 |
+
{
|
| 72 |
+
static void *volatile lock = NULL;
|
| 73 |
+
|
| 74 |
+
while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) {
|
| 75 |
+
/* should ideally do a spin loop instruction here, but
|
| 76 |
+
hard to do it portably and doesn't really matter I
|
| 77 |
+
think: pthread_mutex_init() should be very fast, and
|
| 78 |
+
this is only run at start-up anyway. */
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
#ifdef WITH_THREAD
|
| 82 |
+
if (!_cffi_embed_startup_lock_ready) {
|
| 83 |
+
# ifndef _MSC_VER
|
| 84 |
+
pthread_mutexattr_t attr;
|
| 85 |
+
pthread_mutexattr_init(&attr);
|
| 86 |
+
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
|
| 87 |
+
pthread_mutex_init(&_cffi_embed_startup_lock, &attr);
|
| 88 |
+
# else
|
| 89 |
+
InitializeCriticalSection(&_cffi_embed_startup_lock);
|
| 90 |
+
# endif
|
| 91 |
+
_cffi_embed_startup_lock_ready = 1;
|
| 92 |
+
}
|
| 93 |
+
#endif
|
| 94 |
+
|
| 95 |
+
while (!cffi_compare_and_swap(&lock, (void *)1, NULL))
|
| 96 |
+
;
|
| 97 |
+
|
| 98 |
+
#ifndef _MSC_VER
|
| 99 |
+
pthread_mutex_lock(&_cffi_embed_startup_lock);
|
| 100 |
+
#else
|
| 101 |
+
EnterCriticalSection(&_cffi_embed_startup_lock);
|
| 102 |
+
#endif
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
static void _cffi_release_reentrant_mutex(void)
|
| 106 |
+
{
|
| 107 |
+
#ifndef _MSC_VER
|
| 108 |
+
pthread_mutex_unlock(&_cffi_embed_startup_lock);
|
| 109 |
+
#else
|
| 110 |
+
LeaveCriticalSection(&_cffi_embed_startup_lock);
|
| 111 |
+
#endif
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
/********** CPython-specific section **********/
|
| 116 |
+
#ifndef PYPY_VERSION
|
| 117 |
+
|
| 118 |
+
#include "_cffi_errors.h"
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
#define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX]
|
| 122 |
+
|
| 123 |
+
PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */
|
| 124 |
+
|
| 125 |
+
static void _cffi_py_initialize(void)
|
| 126 |
+
{
|
| 127 |
+
/* XXX use initsigs=0, which "skips initialization registration of
|
| 128 |
+
signal handlers, which might be useful when Python is
|
| 129 |
+
embedded" according to the Python docs. But review and think
|
| 130 |
+
if it should be a user-controllable setting.
|
| 131 |
+
|
| 132 |
+
XXX we should also give a way to write errors to a buffer
|
| 133 |
+
instead of to stderr.
|
| 134 |
+
|
| 135 |
+
XXX if importing 'site' fails, CPython (any version) calls
|
| 136 |
+
exit(). Should we try to work around this behavior here?
|
| 137 |
+
*/
|
| 138 |
+
Py_InitializeEx(0);
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
static int _cffi_initialize_python(void)
|
| 142 |
+
{
|
| 143 |
+
/* This initializes Python, imports _cffi_backend, and then the
|
| 144 |
+
present .dll/.so is set up as a CPython C extension module.
|
| 145 |
+
*/
|
| 146 |
+
int result;
|
| 147 |
+
PyGILState_STATE state;
|
| 148 |
+
PyObject *pycode=NULL, *global_dict=NULL, *x;
|
| 149 |
+
PyObject *builtins;
|
| 150 |
+
|
| 151 |
+
state = PyGILState_Ensure();
|
| 152 |
+
|
| 153 |
+
/* Call the initxxx() function from the present module. It will
|
| 154 |
+
create and initialize us as a CPython extension module, instead
|
| 155 |
+
of letting the startup Python code do it---it might reimport
|
| 156 |
+
the same .dll/.so and get maybe confused on some platforms.
|
| 157 |
+
It might also have troubles locating the .dll/.so again for all
|
| 158 |
+
I know.
|
| 159 |
+
*/
|
| 160 |
+
(void)_CFFI_PYTHON_STARTUP_FUNC();
|
| 161 |
+
if (PyErr_Occurred())
|
| 162 |
+
goto error;
|
| 163 |
+
|
| 164 |
+
/* Now run the Python code provided to ffi.embedding_init_code().
|
| 165 |
+
*/
|
| 166 |
+
pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE,
|
| 167 |
+
"<init code for '" _CFFI_MODULE_NAME "'>",
|
| 168 |
+
Py_file_input);
|
| 169 |
+
if (pycode == NULL)
|
| 170 |
+
goto error;
|
| 171 |
+
global_dict = PyDict_New();
|
| 172 |
+
if (global_dict == NULL)
|
| 173 |
+
goto error;
|
| 174 |
+
builtins = PyEval_GetBuiltins();
|
| 175 |
+
if (builtins == NULL)
|
| 176 |
+
goto error;
|
| 177 |
+
if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0)
|
| 178 |
+
goto error;
|
| 179 |
+
x = PyEval_EvalCode(
|
| 180 |
+
#if PY_MAJOR_VERSION < 3
|
| 181 |
+
(PyCodeObject *)
|
| 182 |
+
#endif
|
| 183 |
+
pycode, global_dict, global_dict);
|
| 184 |
+
if (x == NULL)
|
| 185 |
+
goto error;
|
| 186 |
+
Py_DECREF(x);
|
| 187 |
+
|
| 188 |
+
/* Done! Now if we've been called from
|
| 189 |
+
_cffi_start_and_call_python() in an ``extern "Python"``, we can
|
| 190 |
+
only hope that the Python code did correctly set up the
|
| 191 |
+
corresponding @ffi.def_extern() function. Otherwise, the
|
| 192 |
+
general logic of ``extern "Python"`` functions (inside the
|
| 193 |
+
_cffi_backend module) will find that the reference is still
|
| 194 |
+
missing and print an error.
|
| 195 |
+
*/
|
| 196 |
+
result = 0;
|
| 197 |
+
done:
|
| 198 |
+
Py_XDECREF(pycode);
|
| 199 |
+
Py_XDECREF(global_dict);
|
| 200 |
+
PyGILState_Release(state);
|
| 201 |
+
return result;
|
| 202 |
+
|
| 203 |
+
error:;
|
| 204 |
+
{
|
| 205 |
+
/* Print as much information as potentially useful.
|
| 206 |
+
Debugging load-time failures with embedding is not fun
|
| 207 |
+
*/
|
| 208 |
+
PyObject *ecap;
|
| 209 |
+
PyObject *exception, *v, *tb, *f, *modules, *mod;
|
| 210 |
+
PyErr_Fetch(&exception, &v, &tb);
|
| 211 |
+
ecap = _cffi_start_error_capture();
|
| 212 |
+
f = PySys_GetObject((char *)"stderr");
|
| 213 |
+
if (f != NULL && f != Py_None) {
|
| 214 |
+
PyFile_WriteString(
|
| 215 |
+
"Failed to initialize the Python-CFFI embedding logic:\n\n", f);
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
if (exception != NULL) {
|
| 219 |
+
PyErr_NormalizeException(&exception, &v, &tb);
|
| 220 |
+
PyErr_Display(exception, v, tb);
|
| 221 |
+
}
|
| 222 |
+
Py_XDECREF(exception);
|
| 223 |
+
Py_XDECREF(v);
|
| 224 |
+
Py_XDECREF(tb);
|
| 225 |
+
|
| 226 |
+
if (f != NULL && f != Py_None) {
|
| 227 |
+
PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME
|
| 228 |
+
"\ncompiled with cffi version: 2.0.0"
|
| 229 |
+
"\n_cffi_backend module: ", f);
|
| 230 |
+
modules = PyImport_GetModuleDict();
|
| 231 |
+
mod = PyDict_GetItemString(modules, "_cffi_backend");
|
| 232 |
+
if (mod == NULL) {
|
| 233 |
+
PyFile_WriteString("not loaded", f);
|
| 234 |
+
}
|
| 235 |
+
else {
|
| 236 |
+
v = PyObject_GetAttrString(mod, "__file__");
|
| 237 |
+
PyFile_WriteObject(v, f, 0);
|
| 238 |
+
Py_XDECREF(v);
|
| 239 |
+
}
|
| 240 |
+
PyFile_WriteString("\nsys.path: ", f);
|
| 241 |
+
PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0);
|
| 242 |
+
PyFile_WriteString("\n\n", f);
|
| 243 |
+
}
|
| 244 |
+
_cffi_stop_error_capture(ecap);
|
| 245 |
+
}
|
| 246 |
+
result = -1;
|
| 247 |
+
goto done;
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
#if PY_VERSION_HEX < 0x03080000
|
| 251 |
+
PyAPI_DATA(char *) _PyParser_TokenNames[]; /* from CPython */
|
| 252 |
+
#endif
|
| 253 |
+
|
| 254 |
+
static int _cffi_carefully_make_gil(void)
|
| 255 |
+
{
|
| 256 |
+
/* This does the basic initialization of Python. It can be called
|
| 257 |
+
completely concurrently from unrelated threads. It assumes
|
| 258 |
+
that we don't hold the GIL before (if it exists), and we don't
|
| 259 |
+
hold it afterwards.
|
| 260 |
+
|
| 261 |
+
(What it really does used to be completely different in Python 2
|
| 262 |
+
and Python 3, with the Python 2 solution avoiding the spin-lock
|
| 263 |
+
around the Py_InitializeEx() call. However, after recent changes
|
| 264 |
+
to CPython 2.7 (issue #358) it no longer works. So we use the
|
| 265 |
+
Python 3 solution everywhere.)
|
| 266 |
+
|
| 267 |
+
This initializes Python by calling Py_InitializeEx().
|
| 268 |
+
Important: this must not be called concurrently at all.
|
| 269 |
+
So we use a global variable as a simple spin lock. This global
|
| 270 |
+
variable must be from 'libpythonX.Y.so', not from this
|
| 271 |
+
cffi-based extension module, because it must be shared from
|
| 272 |
+
different cffi-based extension modules.
|
| 273 |
+
|
| 274 |
+
In Python < 3.8, we choose
|
| 275 |
+
_PyParser_TokenNames[0] as a completely arbitrary pointer value
|
| 276 |
+
that is never written to. The default is to point to the
|
| 277 |
+
string "ENDMARKER". We change it temporarily to point to the
|
| 278 |
+
next character in that string. (Yes, I know it's REALLY
|
| 279 |
+
obscure.)
|
| 280 |
+
|
| 281 |
+
In Python >= 3.8, this string array is no longer writable, so
|
| 282 |
+
instead we pick PyCapsuleType.tp_version_tag. We can't change
|
| 283 |
+
Python < 3.8 because someone might use a mixture of cffi
|
| 284 |
+
embedded modules, some of which were compiled before this file
|
| 285 |
+
changed.
|
| 286 |
+
|
| 287 |
+
In Python >= 3.12, this stopped working because that particular
|
| 288 |
+
tp_version_tag gets modified during interpreter startup. It's
|
| 289 |
+
arguably a bad idea before 3.12 too, but again we can't change
|
| 290 |
+
that because someone might use a mixture of cffi embedded
|
| 291 |
+
modules, and no-one reported a bug so far. In Python >= 3.12
|
| 292 |
+
we go instead for PyCapsuleType.tp_as_buffer, which is supposed
|
| 293 |
+
to always be NULL. We write to it temporarily a pointer to
|
| 294 |
+
a struct full of NULLs, which is semantically the same.
|
| 295 |
+
*/
|
| 296 |
+
|
| 297 |
+
#ifdef WITH_THREAD
|
| 298 |
+
# if PY_VERSION_HEX < 0x03080000
|
| 299 |
+
char *volatile *lock = (char *volatile *)_PyParser_TokenNames;
|
| 300 |
+
char *old_value, *locked_value;
|
| 301 |
+
|
| 302 |
+
while (1) { /* spin loop */
|
| 303 |
+
old_value = *lock;
|
| 304 |
+
locked_value = old_value + 1;
|
| 305 |
+
if (old_value[0] == 'E') {
|
| 306 |
+
assert(old_value[1] == 'N');
|
| 307 |
+
if (cffi_compare_and_swap(lock, old_value, locked_value))
|
| 308 |
+
break;
|
| 309 |
+
}
|
| 310 |
+
else {
|
| 311 |
+
assert(old_value[0] == 'N');
|
| 312 |
+
/* should ideally do a spin loop instruction here, but
|
| 313 |
+
hard to do it portably and doesn't really matter I
|
| 314 |
+
think: PyEval_InitThreads() should be very fast, and
|
| 315 |
+
this is only run at start-up anyway. */
|
| 316 |
+
}
|
| 317 |
+
}
|
| 318 |
+
# else
|
| 319 |
+
# if PY_VERSION_HEX < 0x030C0000
|
| 320 |
+
int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag;
|
| 321 |
+
int old_value, locked_value = -42;
|
| 322 |
+
assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG));
|
| 323 |
+
# else
|
| 324 |
+
static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs;
|
| 325 |
+
empty_buffer_procs.mark = -42;
|
| 326 |
+
PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *)
|
| 327 |
+
&PyCapsule_Type.tp_as_buffer;
|
| 328 |
+
PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf;
|
| 329 |
+
# endif
|
| 330 |
+
|
| 331 |
+
while (1) { /* spin loop */
|
| 332 |
+
old_value = *lock;
|
| 333 |
+
if (old_value == 0) {
|
| 334 |
+
if (cffi_compare_and_swap(lock, old_value, locked_value))
|
| 335 |
+
break;
|
| 336 |
+
}
|
| 337 |
+
else {
|
| 338 |
+
# if PY_VERSION_HEX < 0x030C0000
|
| 339 |
+
assert(old_value == locked_value);
|
| 340 |
+
# else
|
| 341 |
+
/* The pointer should point to a possibly different
|
| 342 |
+
empty_buffer_procs from another C extension module */
|
| 343 |
+
assert(((struct ebp_s *)old_value)->mark == -42);
|
| 344 |
+
# endif
|
| 345 |
+
/* should ideally do a spin loop instruction here, but
|
| 346 |
+
hard to do it portably and doesn't really matter I
|
| 347 |
+
think: PyEval_InitThreads() should be very fast, and
|
| 348 |
+
this is only run at start-up anyway. */
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
# endif
|
| 352 |
+
#endif
|
| 353 |
+
|
| 354 |
+
/* call Py_InitializeEx() */
|
| 355 |
+
if (!Py_IsInitialized()) {
|
| 356 |
+
_cffi_py_initialize();
|
| 357 |
+
#if PY_VERSION_HEX < 0x03070000
|
| 358 |
+
PyEval_InitThreads();
|
| 359 |
+
#endif
|
| 360 |
+
PyEval_SaveThread(); /* release the GIL */
|
| 361 |
+
/* the returned tstate must be the one that has been stored into the
|
| 362 |
+
autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */
|
| 363 |
+
}
|
| 364 |
+
else {
|
| 365 |
+
#if PY_VERSION_HEX < 0x03070000
|
| 366 |
+
/* PyEval_InitThreads() is always a no-op from CPython 3.7 */
|
| 367 |
+
PyGILState_STATE state = PyGILState_Ensure();
|
| 368 |
+
PyEval_InitThreads();
|
| 369 |
+
PyGILState_Release(state);
|
| 370 |
+
#endif
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
#ifdef WITH_THREAD
|
| 374 |
+
/* release the lock */
|
| 375 |
+
while (!cffi_compare_and_swap(lock, locked_value, old_value))
|
| 376 |
+
;
|
| 377 |
+
#endif
|
| 378 |
+
|
| 379 |
+
return 0;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
/********** end CPython-specific section **********/
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
#else
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
/********** PyPy-specific section **********/
|
| 389 |
+
|
| 390 |
+
PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */
|
| 391 |
+
|
| 392 |
+
static struct _cffi_pypy_init_s {
|
| 393 |
+
const char *name;
|
| 394 |
+
void *func; /* function pointer */
|
| 395 |
+
const char *code;
|
| 396 |
+
} _cffi_pypy_init = {
|
| 397 |
+
_CFFI_MODULE_NAME,
|
| 398 |
+
_CFFI_PYTHON_STARTUP_FUNC,
|
| 399 |
+
_CFFI_PYTHON_STARTUP_CODE,
|
| 400 |
+
};
|
| 401 |
+
|
| 402 |
+
extern int pypy_carefully_make_gil(const char *);
|
| 403 |
+
extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *);
|
| 404 |
+
|
| 405 |
+
static int _cffi_carefully_make_gil(void)
|
| 406 |
+
{
|
| 407 |
+
return pypy_carefully_make_gil(_CFFI_MODULE_NAME);
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
static int _cffi_initialize_python(void)
|
| 411 |
+
{
|
| 412 |
+
return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init);
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
/********** end PyPy-specific section **********/
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
#endif
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
#ifdef __GNUC__
|
| 422 |
+
__attribute__((noinline))
|
| 423 |
+
#endif
|
| 424 |
+
static _cffi_call_python_fnptr _cffi_start_python(void)
|
| 425 |
+
{
|
| 426 |
+
/* Delicate logic to initialize Python. This function can be
|
| 427 |
+
called multiple times concurrently, e.g. when the process calls
|
| 428 |
+
its first ``extern "Python"`` functions in multiple threads at
|
| 429 |
+
once. It can also be called recursively, in which case we must
|
| 430 |
+
ignore it. We also have to consider what occurs if several
|
| 431 |
+
different cffi-based extensions reach this code in parallel
|
| 432 |
+
threads---it is a different copy of the code, then, and we
|
| 433 |
+
can't have any shared global variable unless it comes from
|
| 434 |
+
'libpythonX.Y.so'.
|
| 435 |
+
|
| 436 |
+
Idea:
|
| 437 |
+
|
| 438 |
+
* _cffi_carefully_make_gil(): "carefully" call
|
| 439 |
+
PyEval_InitThreads() (possibly with Py_InitializeEx() first).
|
| 440 |
+
|
| 441 |
+
* then we use a (local) custom lock to make sure that a call to this
|
| 442 |
+
cffi-based extension will wait if another call to the *same*
|
| 443 |
+
extension is running the initialization in another thread.
|
| 444 |
+
It is reentrant, so that a recursive call will not block, but
|
| 445 |
+
only one from a different thread.
|
| 446 |
+
|
| 447 |
+
* then we grab the GIL and (Python 2) we call Py_InitializeEx().
|
| 448 |
+
At this point, concurrent calls to Py_InitializeEx() are not
|
| 449 |
+
possible: we have the GIL.
|
| 450 |
+
|
| 451 |
+
* do the rest of the specific initialization, which may
|
| 452 |
+
temporarily release the GIL but not the custom lock.
|
| 453 |
+
Only release the custom lock when we are done.
|
| 454 |
+
*/
|
| 455 |
+
static char called = 0;
|
| 456 |
+
|
| 457 |
+
if (_cffi_carefully_make_gil() != 0)
|
| 458 |
+
return NULL;
|
| 459 |
+
|
| 460 |
+
_cffi_acquire_reentrant_mutex();
|
| 461 |
+
|
| 462 |
+
/* Here the GIL exists, but we don't have it. We're only protected
|
| 463 |
+
from concurrency by the reentrant mutex. */
|
| 464 |
+
|
| 465 |
+
/* This file only initializes the embedded module once, the first
|
| 466 |
+
time this is called, even if there are subinterpreters. */
|
| 467 |
+
if (!called) {
|
| 468 |
+
called = 1; /* invoke _cffi_initialize_python() only once,
|
| 469 |
+
but don't set '_cffi_call_python' right now,
|
| 470 |
+
otherwise concurrent threads won't call
|
| 471 |
+
this function at all (we need them to wait) */
|
| 472 |
+
if (_cffi_initialize_python() == 0) {
|
| 473 |
+
/* now initialization is finished. Switch to the fast-path. */
|
| 474 |
+
|
| 475 |
+
/* We would like nobody to see the new value of
|
| 476 |
+
'_cffi_call_python' without also seeing the rest of the
|
| 477 |
+
data initialized. However, this is not possible. But
|
| 478 |
+
the new value of '_cffi_call_python' is the function
|
| 479 |
+
'cffi_call_python()' from _cffi_backend. So: */
|
| 480 |
+
cffi_write_barrier();
|
| 481 |
+
/* ^^^ we put a write barrier here, and a corresponding
|
| 482 |
+
read barrier at the start of cffi_call_python(). This
|
| 483 |
+
ensures that after that read barrier, we see everything
|
| 484 |
+
done here before the write barrier.
|
| 485 |
+
*/
|
| 486 |
+
|
| 487 |
+
assert(_cffi_call_python_org != NULL);
|
| 488 |
+
_cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org;
|
| 489 |
+
}
|
| 490 |
+
else {
|
| 491 |
+
/* initialization failed. Reset this to NULL, even if it was
|
| 492 |
+
already set to some other value. Future calls to
|
| 493 |
+
_cffi_start_python() are still forced to occur, and will
|
| 494 |
+
always return NULL from now on. */
|
| 495 |
+
_cffi_call_python_org = NULL;
|
| 496 |
+
}
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
_cffi_release_reentrant_mutex();
|
| 500 |
+
|
| 501 |
+
return (_cffi_call_python_fnptr)_cffi_call_python_org;
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
static
|
| 505 |
+
void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args)
|
| 506 |
+
{
|
| 507 |
+
_cffi_call_python_fnptr fnptr;
|
| 508 |
+
int current_err = errno;
|
| 509 |
+
#ifdef _MSC_VER
|
| 510 |
+
int current_lasterr = GetLastError();
|
| 511 |
+
#endif
|
| 512 |
+
fnptr = _cffi_start_python();
|
| 513 |
+
if (fnptr == NULL) {
|
| 514 |
+
fprintf(stderr, "function %s() called, but initialization code "
|
| 515 |
+
"failed. Returning 0.\n", externpy->name);
|
| 516 |
+
memset(args, 0, externpy->size_of_result);
|
| 517 |
+
}
|
| 518 |
+
#ifdef _MSC_VER
|
| 519 |
+
SetLastError(current_lasterr);
|
| 520 |
+
#endif
|
| 521 |
+
errno = current_err;
|
| 522 |
+
|
| 523 |
+
if (fnptr != NULL)
|
| 524 |
+
fnptr(externpy, args);
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
/* The cffi_start_python() function makes sure Python is initialized
|
| 529 |
+
and our cffi module is set up. It can be called manually from the
|
| 530 |
+
user C code. The same effect is obtained automatically from any
|
| 531 |
+
dll-exported ``extern "Python"`` function. This function returns
|
| 532 |
+
-1 if initialization failed, 0 if all is OK. */
|
| 533 |
+
_CFFI_UNUSED_FN
|
| 534 |
+
static int cffi_start_python(void)
|
| 535 |
+
{
|
| 536 |
+
if (_cffi_call_python == &_cffi_start_and_call_python) {
|
| 537 |
+
if (_cffi_start_python() == NULL)
|
| 538 |
+
return -1;
|
| 539 |
+
}
|
| 540 |
+
cffi_read_barrier();
|
| 541 |
+
return 0;
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
#undef cffi_compare_and_swap
|
| 545 |
+
#undef cffi_write_barrier
|
| 546 |
+
#undef cffi_read_barrier
|
| 547 |
+
|
| 548 |
+
#ifdef __cplusplus
|
| 549 |
+
}
|
| 550 |
+
#endif
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_imp_emulation.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
try:
|
| 3 |
+
# this works on Python < 3.12
|
| 4 |
+
from imp import *
|
| 5 |
+
|
| 6 |
+
except ImportError:
|
| 7 |
+
# this is a limited emulation for Python >= 3.12.
|
| 8 |
+
# Note that this is used only for tests or for the old ffi.verify().
|
| 9 |
+
# This is copied from the source code of Python 3.11.
|
| 10 |
+
|
| 11 |
+
from _imp import (acquire_lock, release_lock,
|
| 12 |
+
is_builtin, is_frozen)
|
| 13 |
+
|
| 14 |
+
from importlib._bootstrap import _load
|
| 15 |
+
|
| 16 |
+
from importlib import machinery
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import tokenize
|
| 20 |
+
|
| 21 |
+
SEARCH_ERROR = 0
|
| 22 |
+
PY_SOURCE = 1
|
| 23 |
+
PY_COMPILED = 2
|
| 24 |
+
C_EXTENSION = 3
|
| 25 |
+
PY_RESOURCE = 4
|
| 26 |
+
PKG_DIRECTORY = 5
|
| 27 |
+
C_BUILTIN = 6
|
| 28 |
+
PY_FROZEN = 7
|
| 29 |
+
PY_CODERESOURCE = 8
|
| 30 |
+
IMP_HOOK = 9
|
| 31 |
+
|
| 32 |
+
def get_suffixes():
|
| 33 |
+
extensions = [(s, 'rb', C_EXTENSION)
|
| 34 |
+
for s in machinery.EXTENSION_SUFFIXES]
|
| 35 |
+
source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
|
| 36 |
+
bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
|
| 37 |
+
return extensions + source + bytecode
|
| 38 |
+
|
| 39 |
+
def find_module(name, path=None):
|
| 40 |
+
if not isinstance(name, str):
|
| 41 |
+
raise TypeError("'name' must be a str, not {}".format(type(name)))
|
| 42 |
+
elif not isinstance(path, (type(None), list)):
|
| 43 |
+
# Backwards-compatibility
|
| 44 |
+
raise RuntimeError("'path' must be None or a list, "
|
| 45 |
+
"not {}".format(type(path)))
|
| 46 |
+
|
| 47 |
+
if path is None:
|
| 48 |
+
if is_builtin(name):
|
| 49 |
+
return None, None, ('', '', C_BUILTIN)
|
| 50 |
+
elif is_frozen(name):
|
| 51 |
+
return None, None, ('', '', PY_FROZEN)
|
| 52 |
+
else:
|
| 53 |
+
path = sys.path
|
| 54 |
+
|
| 55 |
+
for entry in path:
|
| 56 |
+
package_directory = os.path.join(entry, name)
|
| 57 |
+
for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
|
| 58 |
+
package_file_name = '__init__' + suffix
|
| 59 |
+
file_path = os.path.join(package_directory, package_file_name)
|
| 60 |
+
if os.path.isfile(file_path):
|
| 61 |
+
return None, package_directory, ('', '', PKG_DIRECTORY)
|
| 62 |
+
for suffix, mode, type_ in get_suffixes():
|
| 63 |
+
file_name = name + suffix
|
| 64 |
+
file_path = os.path.join(entry, file_name)
|
| 65 |
+
if os.path.isfile(file_path):
|
| 66 |
+
break
|
| 67 |
+
else:
|
| 68 |
+
continue
|
| 69 |
+
break # Break out of outer loop when breaking out of inner loop.
|
| 70 |
+
else:
|
| 71 |
+
raise ImportError(name, name=name)
|
| 72 |
+
|
| 73 |
+
encoding = None
|
| 74 |
+
if 'b' not in mode:
|
| 75 |
+
with open(file_path, 'rb') as file:
|
| 76 |
+
encoding = tokenize.detect_encoding(file.readline)[0]
|
| 77 |
+
file = open(file_path, mode, encoding=encoding)
|
| 78 |
+
return file, file_path, (suffix, mode, type_)
|
| 79 |
+
|
| 80 |
+
def load_dynamic(name, path, file=None):
|
| 81 |
+
loader = machinery.ExtensionFileLoader(name, path)
|
| 82 |
+
spec = machinery.ModuleSpec(name=name, loader=loader, origin=path)
|
| 83 |
+
return _load(spec)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/_shimmed_dist_utils.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful
|
| 3 |
+
error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken.
|
| 4 |
+
|
| 5 |
+
This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI.
|
| 6 |
+
"""
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
# import setuptools first; this is the most robust way to ensure its embedded distutils is available
|
| 11 |
+
# (the .pth shim should usually work, but this is even more robust)
|
| 12 |
+
import setuptools
|
| 13 |
+
except Exception as ex:
|
| 14 |
+
if sys.version_info >= (3, 12):
|
| 15 |
+
# Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal
|
| 16 |
+
raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex
|
| 17 |
+
|
| 18 |
+
# silently ignore on older Pythons (support fallback to stdlib distutils where available)
|
| 19 |
+
else:
|
| 20 |
+
del setuptools
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
# bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils
|
| 24 |
+
from distutils import log, sysconfig
|
| 25 |
+
from distutils.ccompiler import CCompiler
|
| 26 |
+
from distutils.command.build_ext import build_ext
|
| 27 |
+
from distutils.core import Distribution, Extension
|
| 28 |
+
from distutils.dir_util import mkpath
|
| 29 |
+
from distutils.errors import DistutilsSetupError, CompileError, LinkError
|
| 30 |
+
from distutils.log import set_threshold, set_verbosity
|
| 31 |
+
|
| 32 |
+
if sys.platform == 'win32':
|
| 33 |
+
try:
|
| 34 |
+
# FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler`
|
| 35 |
+
from distutils.msvc9compiler import MSVCCompiler
|
| 36 |
+
except ImportError:
|
| 37 |
+
MSVCCompiler = None
|
| 38 |
+
except Exception as ex:
|
| 39 |
+
if sys.version_info >= (3, 12):
|
| 40 |
+
raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex
|
| 41 |
+
|
| 42 |
+
# anything older, just let the underlying distutils import error fly
|
| 43 |
+
raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex
|
| 44 |
+
|
| 45 |
+
del sys
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/api.py
ADDED
|
@@ -0,0 +1,967 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys, types
|
| 2 |
+
from .lock import allocate_lock
|
| 3 |
+
from .error import CDefError
|
| 4 |
+
from . import model
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
callable
|
| 8 |
+
except NameError:
|
| 9 |
+
# Python 3.1
|
| 10 |
+
from collections import Callable
|
| 11 |
+
callable = lambda x: isinstance(x, Callable)
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
basestring
|
| 15 |
+
except NameError:
|
| 16 |
+
# Python 3.x
|
| 17 |
+
basestring = str
|
| 18 |
+
|
| 19 |
+
_unspecified = object()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class FFI(object):
|
| 24 |
+
r'''
|
| 25 |
+
The main top-level class that you instantiate once, or once per module.
|
| 26 |
+
|
| 27 |
+
Example usage:
|
| 28 |
+
|
| 29 |
+
ffi = FFI()
|
| 30 |
+
ffi.cdef("""
|
| 31 |
+
int printf(const char *, ...);
|
| 32 |
+
""")
|
| 33 |
+
|
| 34 |
+
C = ffi.dlopen(None) # standard library
|
| 35 |
+
-or-
|
| 36 |
+
C = ffi.verify() # use a C compiler: verify the decl above is right
|
| 37 |
+
|
| 38 |
+
C.printf("hello, %s!\n", ffi.new("char[]", "world"))
|
| 39 |
+
'''
|
| 40 |
+
|
| 41 |
+
def __init__(self, backend=None):
|
| 42 |
+
"""Create an FFI instance. The 'backend' argument is used to
|
| 43 |
+
select a non-default backend, mostly for tests.
|
| 44 |
+
"""
|
| 45 |
+
if backend is None:
|
| 46 |
+
# You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with
|
| 47 |
+
# _cffi_backend.so compiled.
|
| 48 |
+
import _cffi_backend as backend
|
| 49 |
+
from . import __version__
|
| 50 |
+
if backend.__version__ != __version__:
|
| 51 |
+
# bad version! Try to be as explicit as possible.
|
| 52 |
+
if hasattr(backend, '__file__'):
|
| 53 |
+
# CPython
|
| 54 |
+
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % (
|
| 55 |
+
__version__, __file__,
|
| 56 |
+
backend.__version__, backend.__file__))
|
| 57 |
+
else:
|
| 58 |
+
# PyPy
|
| 59 |
+
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % (
|
| 60 |
+
__version__, __file__, backend.__version__))
|
| 61 |
+
# (If you insist you can also try to pass the option
|
| 62 |
+
# 'backend=backend_ctypes.CTypesBackend()', but don't
|
| 63 |
+
# rely on it! It's probably not going to work well.)
|
| 64 |
+
|
| 65 |
+
from . import cparser
|
| 66 |
+
self._backend = backend
|
| 67 |
+
self._lock = allocate_lock()
|
| 68 |
+
self._parser = cparser.Parser()
|
| 69 |
+
self._cached_btypes = {}
|
| 70 |
+
self._parsed_types = types.ModuleType('parsed_types').__dict__
|
| 71 |
+
self._new_types = types.ModuleType('new_types').__dict__
|
| 72 |
+
self._function_caches = []
|
| 73 |
+
self._libraries = []
|
| 74 |
+
self._cdefsources = []
|
| 75 |
+
self._included_ffis = []
|
| 76 |
+
self._windows_unicode = None
|
| 77 |
+
self._init_once_cache = {}
|
| 78 |
+
self._cdef_version = None
|
| 79 |
+
self._embedding = None
|
| 80 |
+
self._typecache = model.get_typecache(backend)
|
| 81 |
+
if hasattr(backend, 'set_ffi'):
|
| 82 |
+
backend.set_ffi(self)
|
| 83 |
+
for name in list(backend.__dict__):
|
| 84 |
+
if name.startswith('RTLD_'):
|
| 85 |
+
setattr(self, name, getattr(backend, name))
|
| 86 |
+
#
|
| 87 |
+
with self._lock:
|
| 88 |
+
self.BVoidP = self._get_cached_btype(model.voidp_type)
|
| 89 |
+
self.BCharA = self._get_cached_btype(model.char_array_type)
|
| 90 |
+
if isinstance(backend, types.ModuleType):
|
| 91 |
+
# _cffi_backend: attach these constants to the class
|
| 92 |
+
if not hasattr(FFI, 'NULL'):
|
| 93 |
+
FFI.NULL = self.cast(self.BVoidP, 0)
|
| 94 |
+
FFI.CData, FFI.CType = backend._get_types()
|
| 95 |
+
else:
|
| 96 |
+
# ctypes backend: attach these constants to the instance
|
| 97 |
+
self.NULL = self.cast(self.BVoidP, 0)
|
| 98 |
+
self.CData, self.CType = backend._get_types()
|
| 99 |
+
self.buffer = backend.buffer
|
| 100 |
+
|
| 101 |
+
def cdef(self, csource, override=False, packed=False, pack=None):
|
| 102 |
+
"""Parse the given C source. This registers all declared functions,
|
| 103 |
+
types, and global variables. The functions and global variables can
|
| 104 |
+
then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'.
|
| 105 |
+
The types can be used in 'ffi.new()' and other functions.
|
| 106 |
+
If 'packed' is specified as True, all structs declared inside this
|
| 107 |
+
cdef are packed, i.e. laid out without any field alignment at all.
|
| 108 |
+
Alternatively, 'pack' can be a small integer, and requests for
|
| 109 |
+
alignment greater than that are ignored (pack=1 is equivalent to
|
| 110 |
+
packed=True).
|
| 111 |
+
"""
|
| 112 |
+
self._cdef(csource, override=override, packed=packed, pack=pack)
|
| 113 |
+
|
| 114 |
+
def embedding_api(self, csource, packed=False, pack=None):
|
| 115 |
+
self._cdef(csource, packed=packed, pack=pack, dllexport=True)
|
| 116 |
+
if self._embedding is None:
|
| 117 |
+
self._embedding = ''
|
| 118 |
+
|
| 119 |
+
def _cdef(self, csource, override=False, **options):
|
| 120 |
+
if not isinstance(csource, str): # unicode, on Python 2
|
| 121 |
+
if not isinstance(csource, basestring):
|
| 122 |
+
raise TypeError("cdef() argument must be a string")
|
| 123 |
+
csource = csource.encode('ascii')
|
| 124 |
+
with self._lock:
|
| 125 |
+
self._cdef_version = object()
|
| 126 |
+
self._parser.parse(csource, override=override, **options)
|
| 127 |
+
self._cdefsources.append(csource)
|
| 128 |
+
if override:
|
| 129 |
+
for cache in self._function_caches:
|
| 130 |
+
cache.clear()
|
| 131 |
+
finishlist = self._parser._recomplete
|
| 132 |
+
if finishlist:
|
| 133 |
+
self._parser._recomplete = []
|
| 134 |
+
for tp in finishlist:
|
| 135 |
+
tp.finish_backend_type(self, finishlist)
|
| 136 |
+
|
| 137 |
+
def dlopen(self, name, flags=0):
|
| 138 |
+
"""Load and return a dynamic library identified by 'name'.
|
| 139 |
+
The standard C library can be loaded by passing None.
|
| 140 |
+
Note that functions and types declared by 'ffi.cdef()' are not
|
| 141 |
+
linked to a particular library, just like C headers; in the
|
| 142 |
+
library we only look for the actual (untyped) symbols.
|
| 143 |
+
"""
|
| 144 |
+
if not (isinstance(name, basestring) or
|
| 145 |
+
name is None or
|
| 146 |
+
isinstance(name, self.CData)):
|
| 147 |
+
raise TypeError("dlopen(name): name must be a file name, None, "
|
| 148 |
+
"or an already-opened 'void *' handle")
|
| 149 |
+
with self._lock:
|
| 150 |
+
lib, function_cache = _make_ffi_library(self, name, flags)
|
| 151 |
+
self._function_caches.append(function_cache)
|
| 152 |
+
self._libraries.append(lib)
|
| 153 |
+
return lib
|
| 154 |
+
|
| 155 |
+
def dlclose(self, lib):
|
| 156 |
+
"""Close a library obtained with ffi.dlopen(). After this call,
|
| 157 |
+
access to functions or variables from the library will fail
|
| 158 |
+
(possibly with a segmentation fault).
|
| 159 |
+
"""
|
| 160 |
+
type(lib).__cffi_close__(lib)
|
| 161 |
+
|
| 162 |
+
def _typeof_locked(self, cdecl):
|
| 163 |
+
# call me with the lock!
|
| 164 |
+
key = cdecl
|
| 165 |
+
if key in self._parsed_types:
|
| 166 |
+
return self._parsed_types[key]
|
| 167 |
+
#
|
| 168 |
+
if not isinstance(cdecl, str): # unicode, on Python 2
|
| 169 |
+
cdecl = cdecl.encode('ascii')
|
| 170 |
+
#
|
| 171 |
+
type = self._parser.parse_type(cdecl)
|
| 172 |
+
really_a_function_type = type.is_raw_function
|
| 173 |
+
if really_a_function_type:
|
| 174 |
+
type = type.as_function_pointer()
|
| 175 |
+
btype = self._get_cached_btype(type)
|
| 176 |
+
result = btype, really_a_function_type
|
| 177 |
+
self._parsed_types[key] = result
|
| 178 |
+
return result
|
| 179 |
+
|
| 180 |
+
def _typeof(self, cdecl, consider_function_as_funcptr=False):
|
| 181 |
+
# string -> ctype object
|
| 182 |
+
try:
|
| 183 |
+
result = self._parsed_types[cdecl]
|
| 184 |
+
except KeyError:
|
| 185 |
+
with self._lock:
|
| 186 |
+
result = self._typeof_locked(cdecl)
|
| 187 |
+
#
|
| 188 |
+
btype, really_a_function_type = result
|
| 189 |
+
if really_a_function_type and not consider_function_as_funcptr:
|
| 190 |
+
raise CDefError("the type %r is a function type, not a "
|
| 191 |
+
"pointer-to-function type" % (cdecl,))
|
| 192 |
+
return btype
|
| 193 |
+
|
| 194 |
+
def typeof(self, cdecl):
|
| 195 |
+
"""Parse the C type given as a string and return the
|
| 196 |
+
corresponding <ctype> object.
|
| 197 |
+
It can also be used on 'cdata' instance to get its C type.
|
| 198 |
+
"""
|
| 199 |
+
if isinstance(cdecl, basestring):
|
| 200 |
+
return self._typeof(cdecl)
|
| 201 |
+
if isinstance(cdecl, self.CData):
|
| 202 |
+
return self._backend.typeof(cdecl)
|
| 203 |
+
if isinstance(cdecl, types.BuiltinFunctionType):
|
| 204 |
+
res = _builtin_function_type(cdecl)
|
| 205 |
+
if res is not None:
|
| 206 |
+
return res
|
| 207 |
+
if (isinstance(cdecl, types.FunctionType)
|
| 208 |
+
and hasattr(cdecl, '_cffi_base_type')):
|
| 209 |
+
with self._lock:
|
| 210 |
+
return self._get_cached_btype(cdecl._cffi_base_type)
|
| 211 |
+
raise TypeError(type(cdecl))
|
| 212 |
+
|
| 213 |
+
def sizeof(self, cdecl):
|
| 214 |
+
"""Return the size in bytes of the argument. It can be a
|
| 215 |
+
string naming a C type, or a 'cdata' instance.
|
| 216 |
+
"""
|
| 217 |
+
if isinstance(cdecl, basestring):
|
| 218 |
+
BType = self._typeof(cdecl)
|
| 219 |
+
return self._backend.sizeof(BType)
|
| 220 |
+
else:
|
| 221 |
+
return self._backend.sizeof(cdecl)
|
| 222 |
+
|
| 223 |
+
def alignof(self, cdecl):
|
| 224 |
+
"""Return the natural alignment size in bytes of the C type
|
| 225 |
+
given as a string.
|
| 226 |
+
"""
|
| 227 |
+
if isinstance(cdecl, basestring):
|
| 228 |
+
cdecl = self._typeof(cdecl)
|
| 229 |
+
return self._backend.alignof(cdecl)
|
| 230 |
+
|
| 231 |
+
def offsetof(self, cdecl, *fields_or_indexes):
|
| 232 |
+
"""Return the offset of the named field inside the given
|
| 233 |
+
structure or array, which must be given as a C type name.
|
| 234 |
+
You can give several field names in case of nested structures.
|
| 235 |
+
You can also give numeric values which correspond to array
|
| 236 |
+
items, in case of an array type.
|
| 237 |
+
"""
|
| 238 |
+
if isinstance(cdecl, basestring):
|
| 239 |
+
cdecl = self._typeof(cdecl)
|
| 240 |
+
return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
|
| 241 |
+
|
| 242 |
+
def new(self, cdecl, init=None):
|
| 243 |
+
"""Allocate an instance according to the specified C type and
|
| 244 |
+
return a pointer to it. The specified C type must be either a
|
| 245 |
+
pointer or an array: ``new('X *')`` allocates an X and returns
|
| 246 |
+
a pointer to it, whereas ``new('X[n]')`` allocates an array of
|
| 247 |
+
n X'es and returns an array referencing it (which works
|
| 248 |
+
mostly like a pointer, like in C). You can also use
|
| 249 |
+
``new('X[]', n)`` to allocate an array of a non-constant
|
| 250 |
+
length n.
|
| 251 |
+
|
| 252 |
+
The memory is initialized following the rules of declaring a
|
| 253 |
+
global variable in C: by default it is zero-initialized, but
|
| 254 |
+
an explicit initializer can be given which can be used to
|
| 255 |
+
fill all or part of the memory.
|
| 256 |
+
|
| 257 |
+
When the returned <cdata> object goes out of scope, the memory
|
| 258 |
+
is freed. In other words the returned <cdata> object has
|
| 259 |
+
ownership of the value of type 'cdecl' that it points to. This
|
| 260 |
+
means that the raw data can be used as long as this object is
|
| 261 |
+
kept alive, but must not be used for a longer time. Be careful
|
| 262 |
+
about that when copying the pointer to the memory somewhere
|
| 263 |
+
else, e.g. into another structure.
|
| 264 |
+
"""
|
| 265 |
+
if isinstance(cdecl, basestring):
|
| 266 |
+
cdecl = self._typeof(cdecl)
|
| 267 |
+
return self._backend.newp(cdecl, init)
|
| 268 |
+
|
| 269 |
+
def new_allocator(self, alloc=None, free=None,
|
| 270 |
+
should_clear_after_alloc=True):
|
| 271 |
+
"""Return a new allocator, i.e. a function that behaves like ffi.new()
|
| 272 |
+
but uses the provided low-level 'alloc' and 'free' functions.
|
| 273 |
+
|
| 274 |
+
'alloc' is called with the size as argument. If it returns NULL, a
|
| 275 |
+
MemoryError is raised. 'free' is called with the result of 'alloc'
|
| 276 |
+
as argument. Both can be either Python function or directly C
|
| 277 |
+
functions. If 'free' is None, then no free function is called.
|
| 278 |
+
If both 'alloc' and 'free' are None, the default is used.
|
| 279 |
+
|
| 280 |
+
If 'should_clear_after_alloc' is set to False, then the memory
|
| 281 |
+
returned by 'alloc' is assumed to be already cleared (or you are
|
| 282 |
+
fine with garbage); otherwise CFFI will clear it.
|
| 283 |
+
"""
|
| 284 |
+
compiled_ffi = self._backend.FFI()
|
| 285 |
+
allocator = compiled_ffi.new_allocator(alloc, free,
|
| 286 |
+
should_clear_after_alloc)
|
| 287 |
+
def allocate(cdecl, init=None):
|
| 288 |
+
if isinstance(cdecl, basestring):
|
| 289 |
+
cdecl = self._typeof(cdecl)
|
| 290 |
+
return allocator(cdecl, init)
|
| 291 |
+
return allocate
|
| 292 |
+
|
| 293 |
+
def cast(self, cdecl, source):
|
| 294 |
+
"""Similar to a C cast: returns an instance of the named C
|
| 295 |
+
type initialized with the given 'source'. The source is
|
| 296 |
+
casted between integers or pointers of any type.
|
| 297 |
+
"""
|
| 298 |
+
if isinstance(cdecl, basestring):
|
| 299 |
+
cdecl = self._typeof(cdecl)
|
| 300 |
+
return self._backend.cast(cdecl, source)
|
| 301 |
+
|
| 302 |
+
def string(self, cdata, maxlen=-1):
|
| 303 |
+
"""Return a Python string (or unicode string) from the 'cdata'.
|
| 304 |
+
If 'cdata' is a pointer or array of characters or bytes, returns
|
| 305 |
+
the null-terminated string. The returned string extends until
|
| 306 |
+
the first null character, or at most 'maxlen' characters. If
|
| 307 |
+
'cdata' is an array then 'maxlen' defaults to its length.
|
| 308 |
+
|
| 309 |
+
If 'cdata' is a pointer or array of wchar_t, returns a unicode
|
| 310 |
+
string following the same rules.
|
| 311 |
+
|
| 312 |
+
If 'cdata' is a single character or byte or a wchar_t, returns
|
| 313 |
+
it as a string or unicode string.
|
| 314 |
+
|
| 315 |
+
If 'cdata' is an enum, returns the value of the enumerator as a
|
| 316 |
+
string, or 'NUMBER' if the value is out of range.
|
| 317 |
+
"""
|
| 318 |
+
return self._backend.string(cdata, maxlen)
|
| 319 |
+
|
| 320 |
+
def unpack(self, cdata, length):
|
| 321 |
+
"""Unpack an array of C data of the given length,
|
| 322 |
+
returning a Python string/unicode/list.
|
| 323 |
+
|
| 324 |
+
If 'cdata' is a pointer to 'char', returns a byte string.
|
| 325 |
+
It does not stop at the first null. This is equivalent to:
|
| 326 |
+
ffi.buffer(cdata, length)[:]
|
| 327 |
+
|
| 328 |
+
If 'cdata' is a pointer to 'wchar_t', returns a unicode string.
|
| 329 |
+
'length' is measured in wchar_t's; it is not the size in bytes.
|
| 330 |
+
|
| 331 |
+
If 'cdata' is a pointer to anything else, returns a list of
|
| 332 |
+
'length' items. This is a faster equivalent to:
|
| 333 |
+
[cdata[i] for i in range(length)]
|
| 334 |
+
"""
|
| 335 |
+
return self._backend.unpack(cdata, length)
|
| 336 |
+
|
| 337 |
+
#def buffer(self, cdata, size=-1):
|
| 338 |
+
# """Return a read-write buffer object that references the raw C data
|
| 339 |
+
# pointed to by the given 'cdata'. The 'cdata' must be a pointer or
|
| 340 |
+
# an array. Can be passed to functions expecting a buffer, or directly
|
| 341 |
+
# manipulated with:
|
| 342 |
+
#
|
| 343 |
+
# buf[:] get a copy of it in a regular string, or
|
| 344 |
+
# buf[idx] as a single character
|
| 345 |
+
# buf[:] = ...
|
| 346 |
+
# buf[idx] = ... change the content
|
| 347 |
+
# """
|
| 348 |
+
# note that 'buffer' is a type, set on this instance by __init__
|
| 349 |
+
|
| 350 |
+
def from_buffer(self, cdecl, python_buffer=_unspecified,
|
| 351 |
+
require_writable=False):
|
| 352 |
+
"""Return a cdata of the given type pointing to the data of the
|
| 353 |
+
given Python object, which must support the buffer interface.
|
| 354 |
+
Note that this is not meant to be used on the built-in types
|
| 355 |
+
str or unicode (you can build 'char[]' arrays explicitly)
|
| 356 |
+
but only on objects containing large quantities of raw data
|
| 357 |
+
in some other format, like 'array.array' or numpy arrays.
|
| 358 |
+
|
| 359 |
+
The first argument is optional and default to 'char[]'.
|
| 360 |
+
"""
|
| 361 |
+
if python_buffer is _unspecified:
|
| 362 |
+
cdecl, python_buffer = self.BCharA, cdecl
|
| 363 |
+
elif isinstance(cdecl, basestring):
|
| 364 |
+
cdecl = self._typeof(cdecl)
|
| 365 |
+
return self._backend.from_buffer(cdecl, python_buffer,
|
| 366 |
+
require_writable)
|
| 367 |
+
|
| 368 |
+
def memmove(self, dest, src, n):
|
| 369 |
+
"""ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.
|
| 370 |
+
|
| 371 |
+
Like the C function memmove(), the memory areas may overlap;
|
| 372 |
+
apart from that it behaves like the C function memcpy().
|
| 373 |
+
|
| 374 |
+
'src' can be any cdata ptr or array, or any Python buffer object.
|
| 375 |
+
'dest' can be any cdata ptr or array, or a writable Python buffer
|
| 376 |
+
object. The size to copy, 'n', is always measured in bytes.
|
| 377 |
+
|
| 378 |
+
Unlike other methods, this one supports all Python buffer including
|
| 379 |
+
byte strings and bytearrays---but it still does not support
|
| 380 |
+
non-contiguous buffers.
|
| 381 |
+
"""
|
| 382 |
+
return self._backend.memmove(dest, src, n)
|
| 383 |
+
|
| 384 |
+
def callback(self, cdecl, python_callable=None, error=None, onerror=None):
|
| 385 |
+
"""Return a callback object or a decorator making such a
|
| 386 |
+
callback object. 'cdecl' must name a C function pointer type.
|
| 387 |
+
The callback invokes the specified 'python_callable' (which may
|
| 388 |
+
be provided either directly or via a decorator). Important: the
|
| 389 |
+
callback object must be manually kept alive for as long as the
|
| 390 |
+
callback may be invoked from the C level.
|
| 391 |
+
"""
|
| 392 |
+
def callback_decorator_wrap(python_callable):
|
| 393 |
+
if not callable(python_callable):
|
| 394 |
+
raise TypeError("the 'python_callable' argument "
|
| 395 |
+
"is not callable")
|
| 396 |
+
return self._backend.callback(cdecl, python_callable,
|
| 397 |
+
error, onerror)
|
| 398 |
+
if isinstance(cdecl, basestring):
|
| 399 |
+
cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
|
| 400 |
+
if python_callable is None:
|
| 401 |
+
return callback_decorator_wrap # decorator mode
|
| 402 |
+
else:
|
| 403 |
+
return callback_decorator_wrap(python_callable) # direct mode
|
| 404 |
+
|
| 405 |
+
def getctype(self, cdecl, replace_with=''):
|
| 406 |
+
"""Return a string giving the C type 'cdecl', which may be itself
|
| 407 |
+
a string or a <ctype> object. If 'replace_with' is given, it gives
|
| 408 |
+
extra text to append (or insert for more complicated C types), like
|
| 409 |
+
a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
|
| 410 |
+
"""
|
| 411 |
+
if isinstance(cdecl, basestring):
|
| 412 |
+
cdecl = self._typeof(cdecl)
|
| 413 |
+
replace_with = replace_with.strip()
|
| 414 |
+
if (replace_with.startswith('*')
|
| 415 |
+
and '&[' in self._backend.getcname(cdecl, '&')):
|
| 416 |
+
replace_with = '(%s)' % replace_with
|
| 417 |
+
elif replace_with and not replace_with[0] in '[(':
|
| 418 |
+
replace_with = ' ' + replace_with
|
| 419 |
+
return self._backend.getcname(cdecl, replace_with)
|
| 420 |
+
|
| 421 |
+
def gc(self, cdata, destructor, size=0):
|
| 422 |
+
"""Return a new cdata object that points to the same
|
| 423 |
+
data. Later, when this new cdata object is garbage-collected,
|
| 424 |
+
'destructor(old_cdata_object)' will be called.
|
| 425 |
+
|
| 426 |
+
The optional 'size' gives an estimate of the size, used to
|
| 427 |
+
trigger the garbage collection more eagerly. So far only used
|
| 428 |
+
on PyPy. It tells the GC that the returned object keeps alive
|
| 429 |
+
roughly 'size' bytes of external memory.
|
| 430 |
+
"""
|
| 431 |
+
return self._backend.gcp(cdata, destructor, size)
|
| 432 |
+
|
| 433 |
+
def _get_cached_btype(self, type):
|
| 434 |
+
assert self._lock.acquire(False) is False
|
| 435 |
+
# call me with the lock!
|
| 436 |
+
try:
|
| 437 |
+
BType = self._cached_btypes[type]
|
| 438 |
+
except KeyError:
|
| 439 |
+
finishlist = []
|
| 440 |
+
BType = type.get_cached_btype(self, finishlist)
|
| 441 |
+
for type in finishlist:
|
| 442 |
+
type.finish_backend_type(self, finishlist)
|
| 443 |
+
return BType
|
| 444 |
+
|
| 445 |
+
def verify(self, source='', tmpdir=None, **kwargs):
|
| 446 |
+
"""Verify that the current ffi signatures compile on this
|
| 447 |
+
machine, and return a dynamic library object. The dynamic
|
| 448 |
+
library can be used to call functions and access global
|
| 449 |
+
variables declared in this 'ffi'. The library is compiled
|
| 450 |
+
by the C compiler: it gives you C-level API compatibility
|
| 451 |
+
(including calling macros). This is unlike 'ffi.dlopen()',
|
| 452 |
+
which requires binary compatibility in the signatures.
|
| 453 |
+
"""
|
| 454 |
+
from .verifier import Verifier, _caller_dir_pycache
|
| 455 |
+
#
|
| 456 |
+
# If set_unicode(True) was called, insert the UNICODE and
|
| 457 |
+
# _UNICODE macro declarations
|
| 458 |
+
if self._windows_unicode:
|
| 459 |
+
self._apply_windows_unicode(kwargs)
|
| 460 |
+
#
|
| 461 |
+
# Set the tmpdir here, and not in Verifier.__init__: it picks
|
| 462 |
+
# up the caller's directory, which we want to be the caller of
|
| 463 |
+
# ffi.verify(), as opposed to the caller of Veritier().
|
| 464 |
+
tmpdir = tmpdir or _caller_dir_pycache()
|
| 465 |
+
#
|
| 466 |
+
# Make a Verifier() and use it to load the library.
|
| 467 |
+
self.verifier = Verifier(self, source, tmpdir, **kwargs)
|
| 468 |
+
lib = self.verifier.load_library()
|
| 469 |
+
#
|
| 470 |
+
# Save the loaded library for keep-alive purposes, even
|
| 471 |
+
# if the caller doesn't keep it alive itself (it should).
|
| 472 |
+
self._libraries.append(lib)
|
| 473 |
+
return lib
|
| 474 |
+
|
| 475 |
+
def _get_errno(self):
|
| 476 |
+
return self._backend.get_errno()
|
| 477 |
+
def _set_errno(self, errno):
|
| 478 |
+
self._backend.set_errno(errno)
|
| 479 |
+
errno = property(_get_errno, _set_errno, None,
|
| 480 |
+
"the value of 'errno' from/to the C calls")
|
| 481 |
+
|
| 482 |
+
def getwinerror(self, code=-1):
|
| 483 |
+
return self._backend.getwinerror(code)
|
| 484 |
+
|
| 485 |
+
def _pointer_to(self, ctype):
|
| 486 |
+
with self._lock:
|
| 487 |
+
return model.pointer_cache(self, ctype)
|
| 488 |
+
|
| 489 |
+
def addressof(self, cdata, *fields_or_indexes):
|
| 490 |
+
"""Return the address of a <cdata 'struct-or-union'>.
|
| 491 |
+
If 'fields_or_indexes' are given, returns the address of that
|
| 492 |
+
field or array item in the structure or array, recursively in
|
| 493 |
+
case of nested structures.
|
| 494 |
+
"""
|
| 495 |
+
try:
|
| 496 |
+
ctype = self._backend.typeof(cdata)
|
| 497 |
+
except TypeError:
|
| 498 |
+
if '__addressof__' in type(cdata).__dict__:
|
| 499 |
+
return type(cdata).__addressof__(cdata, *fields_or_indexes)
|
| 500 |
+
raise
|
| 501 |
+
if fields_or_indexes:
|
| 502 |
+
ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes)
|
| 503 |
+
else:
|
| 504 |
+
if ctype.kind == "pointer":
|
| 505 |
+
raise TypeError("addressof(pointer)")
|
| 506 |
+
offset = 0
|
| 507 |
+
ctypeptr = self._pointer_to(ctype)
|
| 508 |
+
return self._backend.rawaddressof(ctypeptr, cdata, offset)
|
| 509 |
+
|
| 510 |
+
def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes):
|
| 511 |
+
ctype, offset = self._backend.typeoffsetof(ctype, field_or_index)
|
| 512 |
+
for field1 in fields_or_indexes:
|
| 513 |
+
ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1)
|
| 514 |
+
offset += offset1
|
| 515 |
+
return ctype, offset
|
| 516 |
+
|
| 517 |
+
def include(self, ffi_to_include):
|
| 518 |
+
"""Includes the typedefs, structs, unions and enums defined
|
| 519 |
+
in another FFI instance. Usage is similar to a #include in C,
|
| 520 |
+
where a part of the program might include types defined in
|
| 521 |
+
another part for its own usage. Note that the include()
|
| 522 |
+
method has no effect on functions, constants and global
|
| 523 |
+
variables, which must anyway be accessed directly from the
|
| 524 |
+
lib object returned by the original FFI instance.
|
| 525 |
+
"""
|
| 526 |
+
if not isinstance(ffi_to_include, FFI):
|
| 527 |
+
raise TypeError("ffi.include() expects an argument that is also of"
|
| 528 |
+
" type cffi.FFI, not %r" % (
|
| 529 |
+
type(ffi_to_include).__name__,))
|
| 530 |
+
if ffi_to_include is self:
|
| 531 |
+
raise ValueError("self.include(self)")
|
| 532 |
+
with ffi_to_include._lock:
|
| 533 |
+
with self._lock:
|
| 534 |
+
self._parser.include(ffi_to_include._parser)
|
| 535 |
+
self._cdefsources.append('[')
|
| 536 |
+
self._cdefsources.extend(ffi_to_include._cdefsources)
|
| 537 |
+
self._cdefsources.append(']')
|
| 538 |
+
self._included_ffis.append(ffi_to_include)
|
| 539 |
+
|
| 540 |
+
def new_handle(self, x):
|
| 541 |
+
return self._backend.newp_handle(self.BVoidP, x)
|
| 542 |
+
|
| 543 |
+
def from_handle(self, x):
|
| 544 |
+
return self._backend.from_handle(x)
|
| 545 |
+
|
| 546 |
+
def release(self, x):
|
| 547 |
+
self._backend.release(x)
|
| 548 |
+
|
| 549 |
+
def set_unicode(self, enabled_flag):
|
| 550 |
+
"""Windows: if 'enabled_flag' is True, enable the UNICODE and
|
| 551 |
+
_UNICODE defines in C, and declare the types like TCHAR and LPTCSTR
|
| 552 |
+
to be (pointers to) wchar_t. If 'enabled_flag' is False,
|
| 553 |
+
declare these types to be (pointers to) plain 8-bit characters.
|
| 554 |
+
This is mostly for backward compatibility; you usually want True.
|
| 555 |
+
"""
|
| 556 |
+
if self._windows_unicode is not None:
|
| 557 |
+
raise ValueError("set_unicode() can only be called once")
|
| 558 |
+
enabled_flag = bool(enabled_flag)
|
| 559 |
+
if enabled_flag:
|
| 560 |
+
self.cdef("typedef wchar_t TBYTE;"
|
| 561 |
+
"typedef wchar_t TCHAR;"
|
| 562 |
+
"typedef const wchar_t *LPCTSTR;"
|
| 563 |
+
"typedef const wchar_t *PCTSTR;"
|
| 564 |
+
"typedef wchar_t *LPTSTR;"
|
| 565 |
+
"typedef wchar_t *PTSTR;"
|
| 566 |
+
"typedef TBYTE *PTBYTE;"
|
| 567 |
+
"typedef TCHAR *PTCHAR;")
|
| 568 |
+
else:
|
| 569 |
+
self.cdef("typedef char TBYTE;"
|
| 570 |
+
"typedef char TCHAR;"
|
| 571 |
+
"typedef const char *LPCTSTR;"
|
| 572 |
+
"typedef const char *PCTSTR;"
|
| 573 |
+
"typedef char *LPTSTR;"
|
| 574 |
+
"typedef char *PTSTR;"
|
| 575 |
+
"typedef TBYTE *PTBYTE;"
|
| 576 |
+
"typedef TCHAR *PTCHAR;")
|
| 577 |
+
self._windows_unicode = enabled_flag
|
| 578 |
+
|
| 579 |
+
def _apply_windows_unicode(self, kwds):
|
| 580 |
+
defmacros = kwds.get('define_macros', ())
|
| 581 |
+
if not isinstance(defmacros, (list, tuple)):
|
| 582 |
+
raise TypeError("'define_macros' must be a list or tuple")
|
| 583 |
+
defmacros = list(defmacros) + [('UNICODE', '1'),
|
| 584 |
+
('_UNICODE', '1')]
|
| 585 |
+
kwds['define_macros'] = defmacros
|
| 586 |
+
|
| 587 |
+
def _apply_embedding_fix(self, kwds):
|
| 588 |
+
# must include an argument like "-lpython2.7" for the compiler
|
| 589 |
+
def ensure(key, value):
|
| 590 |
+
lst = kwds.setdefault(key, [])
|
| 591 |
+
if value not in lst:
|
| 592 |
+
lst.append(value)
|
| 593 |
+
#
|
| 594 |
+
if '__pypy__' in sys.builtin_module_names:
|
| 595 |
+
import os
|
| 596 |
+
if sys.platform == "win32":
|
| 597 |
+
# we need 'libpypy-c.lib'. Current distributions of
|
| 598 |
+
# pypy (>= 4.1) contain it as 'libs/python27.lib'.
|
| 599 |
+
pythonlib = "python{0[0]}{0[1]}".format(sys.version_info)
|
| 600 |
+
if hasattr(sys, 'prefix'):
|
| 601 |
+
ensure('library_dirs', os.path.join(sys.prefix, 'libs'))
|
| 602 |
+
else:
|
| 603 |
+
# we need 'libpypy-c.{so,dylib}', which should be by
|
| 604 |
+
# default located in 'sys.prefix/bin' for installed
|
| 605 |
+
# systems.
|
| 606 |
+
if sys.version_info < (3,):
|
| 607 |
+
pythonlib = "pypy-c"
|
| 608 |
+
else:
|
| 609 |
+
pythonlib = "pypy3-c"
|
| 610 |
+
if hasattr(sys, 'prefix'):
|
| 611 |
+
ensure('library_dirs', os.path.join(sys.prefix, 'bin'))
|
| 612 |
+
# On uninstalled pypy's, the libpypy-c is typically found in
|
| 613 |
+
# .../pypy/goal/.
|
| 614 |
+
if hasattr(sys, 'prefix'):
|
| 615 |
+
ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal'))
|
| 616 |
+
else:
|
| 617 |
+
if sys.platform == "win32":
|
| 618 |
+
template = "python%d%d"
|
| 619 |
+
if hasattr(sys, 'gettotalrefcount'):
|
| 620 |
+
template += '_d'
|
| 621 |
+
else:
|
| 622 |
+
try:
|
| 623 |
+
import sysconfig
|
| 624 |
+
except ImportError: # 2.6
|
| 625 |
+
from cffi._shimmed_dist_utils import sysconfig
|
| 626 |
+
template = "python%d.%d"
|
| 627 |
+
if sysconfig.get_config_var('DEBUG_EXT'):
|
| 628 |
+
template += sysconfig.get_config_var('DEBUG_EXT')
|
| 629 |
+
pythonlib = (template %
|
| 630 |
+
(sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
|
| 631 |
+
if hasattr(sys, 'abiflags'):
|
| 632 |
+
pythonlib += sys.abiflags
|
| 633 |
+
ensure('libraries', pythonlib)
|
| 634 |
+
if sys.platform == "win32":
|
| 635 |
+
ensure('extra_link_args', '/MANIFEST')
|
| 636 |
+
|
| 637 |
+
def set_source(self, module_name, source, source_extension='.c', **kwds):
|
| 638 |
+
import os
|
| 639 |
+
if hasattr(self, '_assigned_source'):
|
| 640 |
+
raise ValueError("set_source() cannot be called several times "
|
| 641 |
+
"per ffi object")
|
| 642 |
+
if not isinstance(module_name, basestring):
|
| 643 |
+
raise TypeError("'module_name' must be a string")
|
| 644 |
+
if os.sep in module_name or (os.altsep and os.altsep in module_name):
|
| 645 |
+
raise ValueError("'module_name' must not contain '/': use a dotted "
|
| 646 |
+
"name to make a 'package.module' location")
|
| 647 |
+
self._assigned_source = (str(module_name), source,
|
| 648 |
+
source_extension, kwds)
|
| 649 |
+
|
| 650 |
+
def set_source_pkgconfig(self, module_name, pkgconfig_libs, source,
|
| 651 |
+
source_extension='.c', **kwds):
|
| 652 |
+
from . import pkgconfig
|
| 653 |
+
if not isinstance(pkgconfig_libs, list):
|
| 654 |
+
raise TypeError("the pkgconfig_libs argument must be a list "
|
| 655 |
+
"of package names")
|
| 656 |
+
kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs)
|
| 657 |
+
pkgconfig.merge_flags(kwds, kwds2)
|
| 658 |
+
self.set_source(module_name, source, source_extension, **kwds)
|
| 659 |
+
|
| 660 |
+
def distutils_extension(self, tmpdir='build', verbose=True):
|
| 661 |
+
from cffi._shimmed_dist_utils import mkpath
|
| 662 |
+
from .recompiler import recompile
|
| 663 |
+
#
|
| 664 |
+
if not hasattr(self, '_assigned_source'):
|
| 665 |
+
if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored
|
| 666 |
+
return self.verifier.get_extension()
|
| 667 |
+
raise ValueError("set_source() must be called before"
|
| 668 |
+
" distutils_extension()")
|
| 669 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
| 670 |
+
if source is None:
|
| 671 |
+
raise TypeError("distutils_extension() is only for C extension "
|
| 672 |
+
"modules, not for dlopen()-style pure Python "
|
| 673 |
+
"modules")
|
| 674 |
+
mkpath(tmpdir)
|
| 675 |
+
ext, updated = recompile(self, module_name,
|
| 676 |
+
source, tmpdir=tmpdir, extradir=tmpdir,
|
| 677 |
+
source_extension=source_extension,
|
| 678 |
+
call_c_compiler=False, **kwds)
|
| 679 |
+
if verbose:
|
| 680 |
+
if updated:
|
| 681 |
+
sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
|
| 682 |
+
else:
|
| 683 |
+
sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
|
| 684 |
+
return ext
|
| 685 |
+
|
| 686 |
+
def emit_c_code(self, filename):
|
| 687 |
+
from .recompiler import recompile
|
| 688 |
+
#
|
| 689 |
+
if not hasattr(self, '_assigned_source'):
|
| 690 |
+
raise ValueError("set_source() must be called before emit_c_code()")
|
| 691 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
| 692 |
+
if source is None:
|
| 693 |
+
raise TypeError("emit_c_code() is only for C extension modules, "
|
| 694 |
+
"not for dlopen()-style pure Python modules")
|
| 695 |
+
recompile(self, module_name, source,
|
| 696 |
+
c_file=filename, call_c_compiler=False,
|
| 697 |
+
uses_ffiplatform=False, **kwds)
|
| 698 |
+
|
| 699 |
+
def emit_python_code(self, filename):
|
| 700 |
+
from .recompiler import recompile
|
| 701 |
+
#
|
| 702 |
+
if not hasattr(self, '_assigned_source'):
|
| 703 |
+
raise ValueError("set_source() must be called before emit_c_code()")
|
| 704 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
| 705 |
+
if source is not None:
|
| 706 |
+
raise TypeError("emit_python_code() is only for dlopen()-style "
|
| 707 |
+
"pure Python modules, not for C extension modules")
|
| 708 |
+
recompile(self, module_name, source,
|
| 709 |
+
c_file=filename, call_c_compiler=False,
|
| 710 |
+
uses_ffiplatform=False, **kwds)
|
| 711 |
+
|
| 712 |
+
def compile(self, tmpdir='.', verbose=0, target=None, debug=None):
|
| 713 |
+
"""The 'target' argument gives the final file name of the
|
| 714 |
+
compiled DLL. Use '*' to force distutils' choice, suitable for
|
| 715 |
+
regular CPython C API modules. Use a file name ending in '.*'
|
| 716 |
+
to ask for the system's default extension for dynamic libraries
|
| 717 |
+
(.so/.dll/.dylib).
|
| 718 |
+
|
| 719 |
+
The default is '*' when building a non-embedded C API extension,
|
| 720 |
+
and (module_name + '.*') when building an embedded library.
|
| 721 |
+
"""
|
| 722 |
+
from .recompiler import recompile
|
| 723 |
+
#
|
| 724 |
+
if not hasattr(self, '_assigned_source'):
|
| 725 |
+
raise ValueError("set_source() must be called before compile()")
|
| 726 |
+
module_name, source, source_extension, kwds = self._assigned_source
|
| 727 |
+
return recompile(self, module_name, source, tmpdir=tmpdir,
|
| 728 |
+
target=target, source_extension=source_extension,
|
| 729 |
+
compiler_verbose=verbose, debug=debug, **kwds)
|
| 730 |
+
|
| 731 |
+
def init_once(self, func, tag):
|
| 732 |
+
# Read _init_once_cache[tag], which is either (False, lock) if
|
| 733 |
+
# we're calling the function now in some thread, or (True, result).
|
| 734 |
+
# Don't call setdefault() in most cases, to avoid allocating and
|
| 735 |
+
# immediately freeing a lock; but still use setdefaut() to avoid
|
| 736 |
+
# races.
|
| 737 |
+
try:
|
| 738 |
+
x = self._init_once_cache[tag]
|
| 739 |
+
except KeyError:
|
| 740 |
+
x = self._init_once_cache.setdefault(tag, (False, allocate_lock()))
|
| 741 |
+
# Common case: we got (True, result), so we return the result.
|
| 742 |
+
if x[0]:
|
| 743 |
+
return x[1]
|
| 744 |
+
# Else, it's a lock. Acquire it to serialize the following tests.
|
| 745 |
+
with x[1]:
|
| 746 |
+
# Read again from _init_once_cache the current status.
|
| 747 |
+
x = self._init_once_cache[tag]
|
| 748 |
+
if x[0]:
|
| 749 |
+
return x[1]
|
| 750 |
+
# Call the function and store the result back.
|
| 751 |
+
result = func()
|
| 752 |
+
self._init_once_cache[tag] = (True, result)
|
| 753 |
+
return result
|
| 754 |
+
|
| 755 |
+
def embedding_init_code(self, pysource):
|
| 756 |
+
if self._embedding:
|
| 757 |
+
raise ValueError("embedding_init_code() can only be called once")
|
| 758 |
+
# fix 'pysource' before it gets dumped into the C file:
|
| 759 |
+
# - remove empty lines at the beginning, so it starts at "line 1"
|
| 760 |
+
# - dedent, if all non-empty lines are indented
|
| 761 |
+
# - check for SyntaxErrors
|
| 762 |
+
import re
|
| 763 |
+
match = re.match(r'\s*\n', pysource)
|
| 764 |
+
if match:
|
| 765 |
+
pysource = pysource[match.end():]
|
| 766 |
+
lines = pysource.splitlines() or ['']
|
| 767 |
+
prefix = re.match(r'\s*', lines[0]).group()
|
| 768 |
+
for i in range(1, len(lines)):
|
| 769 |
+
line = lines[i]
|
| 770 |
+
if line.rstrip():
|
| 771 |
+
while not line.startswith(prefix):
|
| 772 |
+
prefix = prefix[:-1]
|
| 773 |
+
i = len(prefix)
|
| 774 |
+
lines = [line[i:]+'\n' for line in lines]
|
| 775 |
+
pysource = ''.join(lines)
|
| 776 |
+
#
|
| 777 |
+
compile(pysource, "cffi_init", "exec")
|
| 778 |
+
#
|
| 779 |
+
self._embedding = pysource
|
| 780 |
+
|
| 781 |
+
def def_extern(self, *args, **kwds):
|
| 782 |
+
raise ValueError("ffi.def_extern() is only available on API-mode FFI "
|
| 783 |
+
"objects")
|
| 784 |
+
|
| 785 |
+
def list_types(self):
|
| 786 |
+
"""Returns the user type names known to this FFI instance.
|
| 787 |
+
This returns a tuple containing three lists of names:
|
| 788 |
+
(typedef_names, names_of_structs, names_of_unions)
|
| 789 |
+
"""
|
| 790 |
+
typedefs = []
|
| 791 |
+
structs = []
|
| 792 |
+
unions = []
|
| 793 |
+
for key in self._parser._declarations:
|
| 794 |
+
if key.startswith('typedef '):
|
| 795 |
+
typedefs.append(key[8:])
|
| 796 |
+
elif key.startswith('struct '):
|
| 797 |
+
structs.append(key[7:])
|
| 798 |
+
elif key.startswith('union '):
|
| 799 |
+
unions.append(key[6:])
|
| 800 |
+
typedefs.sort()
|
| 801 |
+
structs.sort()
|
| 802 |
+
unions.sort()
|
| 803 |
+
return (typedefs, structs, unions)
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
def _load_backend_lib(backend, name, flags):
|
| 807 |
+
import os
|
| 808 |
+
if not isinstance(name, basestring):
|
| 809 |
+
if sys.platform != "win32" or name is not None:
|
| 810 |
+
return backend.load_library(name, flags)
|
| 811 |
+
name = "c" # Windows: load_library(None) fails, but this works
|
| 812 |
+
# on Python 2 (backward compatibility hack only)
|
| 813 |
+
first_error = None
|
| 814 |
+
if '.' in name or '/' in name or os.sep in name:
|
| 815 |
+
try:
|
| 816 |
+
return backend.load_library(name, flags)
|
| 817 |
+
except OSError as e:
|
| 818 |
+
first_error = e
|
| 819 |
+
import ctypes.util
|
| 820 |
+
path = ctypes.util.find_library(name)
|
| 821 |
+
if path is None:
|
| 822 |
+
if name == "c" and sys.platform == "win32" and sys.version_info >= (3,):
|
| 823 |
+
raise OSError("dlopen(None) cannot work on Windows for Python 3 "
|
| 824 |
+
"(see http://bugs.python.org/issue23606)")
|
| 825 |
+
msg = ("ctypes.util.find_library() did not manage "
|
| 826 |
+
"to locate a library called %r" % (name,))
|
| 827 |
+
if first_error is not None:
|
| 828 |
+
msg = "%s. Additionally, %s" % (first_error, msg)
|
| 829 |
+
raise OSError(msg)
|
| 830 |
+
return backend.load_library(path, flags)
|
| 831 |
+
|
| 832 |
+
def _make_ffi_library(ffi, libname, flags):
|
| 833 |
+
backend = ffi._backend
|
| 834 |
+
backendlib = _load_backend_lib(backend, libname, flags)
|
| 835 |
+
#
|
| 836 |
+
def accessor_function(name):
|
| 837 |
+
key = 'function ' + name
|
| 838 |
+
tp, _ = ffi._parser._declarations[key]
|
| 839 |
+
BType = ffi._get_cached_btype(tp)
|
| 840 |
+
value = backendlib.load_function(BType, name)
|
| 841 |
+
library.__dict__[name] = value
|
| 842 |
+
#
|
| 843 |
+
def accessor_variable(name):
|
| 844 |
+
key = 'variable ' + name
|
| 845 |
+
tp, _ = ffi._parser._declarations[key]
|
| 846 |
+
BType = ffi._get_cached_btype(tp)
|
| 847 |
+
read_variable = backendlib.read_variable
|
| 848 |
+
write_variable = backendlib.write_variable
|
| 849 |
+
setattr(FFILibrary, name, property(
|
| 850 |
+
lambda self: read_variable(BType, name),
|
| 851 |
+
lambda self, value: write_variable(BType, name, value)))
|
| 852 |
+
#
|
| 853 |
+
def addressof_var(name):
|
| 854 |
+
try:
|
| 855 |
+
return addr_variables[name]
|
| 856 |
+
except KeyError:
|
| 857 |
+
with ffi._lock:
|
| 858 |
+
if name not in addr_variables:
|
| 859 |
+
key = 'variable ' + name
|
| 860 |
+
tp, _ = ffi._parser._declarations[key]
|
| 861 |
+
BType = ffi._get_cached_btype(tp)
|
| 862 |
+
if BType.kind != 'array':
|
| 863 |
+
BType = model.pointer_cache(ffi, BType)
|
| 864 |
+
p = backendlib.load_function(BType, name)
|
| 865 |
+
addr_variables[name] = p
|
| 866 |
+
return addr_variables[name]
|
| 867 |
+
#
|
| 868 |
+
def accessor_constant(name):
|
| 869 |
+
raise NotImplementedError("non-integer constant '%s' cannot be "
|
| 870 |
+
"accessed from a dlopen() library" % (name,))
|
| 871 |
+
#
|
| 872 |
+
def accessor_int_constant(name):
|
| 873 |
+
library.__dict__[name] = ffi._parser._int_constants[name]
|
| 874 |
+
#
|
| 875 |
+
accessors = {}
|
| 876 |
+
accessors_version = [False]
|
| 877 |
+
addr_variables = {}
|
| 878 |
+
#
|
| 879 |
+
def update_accessors():
|
| 880 |
+
if accessors_version[0] is ffi._cdef_version:
|
| 881 |
+
return
|
| 882 |
+
#
|
| 883 |
+
for key, (tp, _) in ffi._parser._declarations.items():
|
| 884 |
+
if not isinstance(tp, model.EnumType):
|
| 885 |
+
tag, name = key.split(' ', 1)
|
| 886 |
+
if tag == 'function':
|
| 887 |
+
accessors[name] = accessor_function
|
| 888 |
+
elif tag == 'variable':
|
| 889 |
+
accessors[name] = accessor_variable
|
| 890 |
+
elif tag == 'constant':
|
| 891 |
+
accessors[name] = accessor_constant
|
| 892 |
+
else:
|
| 893 |
+
for i, enumname in enumerate(tp.enumerators):
|
| 894 |
+
def accessor_enum(name, tp=tp, i=i):
|
| 895 |
+
tp.check_not_partial()
|
| 896 |
+
library.__dict__[name] = tp.enumvalues[i]
|
| 897 |
+
accessors[enumname] = accessor_enum
|
| 898 |
+
for name in ffi._parser._int_constants:
|
| 899 |
+
accessors.setdefault(name, accessor_int_constant)
|
| 900 |
+
accessors_version[0] = ffi._cdef_version
|
| 901 |
+
#
|
| 902 |
+
def make_accessor(name):
|
| 903 |
+
with ffi._lock:
|
| 904 |
+
if name in library.__dict__ or name in FFILibrary.__dict__:
|
| 905 |
+
return # added by another thread while waiting for the lock
|
| 906 |
+
if name not in accessors:
|
| 907 |
+
update_accessors()
|
| 908 |
+
if name not in accessors:
|
| 909 |
+
raise AttributeError(name)
|
| 910 |
+
accessors[name](name)
|
| 911 |
+
#
|
| 912 |
+
class FFILibrary(object):
|
| 913 |
+
def __getattr__(self, name):
|
| 914 |
+
make_accessor(name)
|
| 915 |
+
return getattr(self, name)
|
| 916 |
+
def __setattr__(self, name, value):
|
| 917 |
+
try:
|
| 918 |
+
property = getattr(self.__class__, name)
|
| 919 |
+
except AttributeError:
|
| 920 |
+
make_accessor(name)
|
| 921 |
+
setattr(self, name, value)
|
| 922 |
+
else:
|
| 923 |
+
property.__set__(self, value)
|
| 924 |
+
def __dir__(self):
|
| 925 |
+
with ffi._lock:
|
| 926 |
+
update_accessors()
|
| 927 |
+
return accessors.keys()
|
| 928 |
+
def __addressof__(self, name):
|
| 929 |
+
if name in library.__dict__:
|
| 930 |
+
return library.__dict__[name]
|
| 931 |
+
if name in FFILibrary.__dict__:
|
| 932 |
+
return addressof_var(name)
|
| 933 |
+
make_accessor(name)
|
| 934 |
+
if name in library.__dict__:
|
| 935 |
+
return library.__dict__[name]
|
| 936 |
+
if name in FFILibrary.__dict__:
|
| 937 |
+
return addressof_var(name)
|
| 938 |
+
raise AttributeError("cffi library has no function or "
|
| 939 |
+
"global variable named '%s'" % (name,))
|
| 940 |
+
def __cffi_close__(self):
|
| 941 |
+
backendlib.close_lib()
|
| 942 |
+
self.__dict__.clear()
|
| 943 |
+
#
|
| 944 |
+
if isinstance(libname, basestring):
|
| 945 |
+
try:
|
| 946 |
+
if not isinstance(libname, str): # unicode, on Python 2
|
| 947 |
+
libname = libname.encode('utf-8')
|
| 948 |
+
FFILibrary.__name__ = 'FFILibrary_%s' % libname
|
| 949 |
+
except UnicodeError:
|
| 950 |
+
pass
|
| 951 |
+
library = FFILibrary()
|
| 952 |
+
return library, library.__dict__
|
| 953 |
+
|
| 954 |
+
def _builtin_function_type(func):
|
| 955 |
+
# a hack to make at least ffi.typeof(builtin_function) work,
|
| 956 |
+
# if the builtin function was obtained by 'vengine_cpy'.
|
| 957 |
+
import sys
|
| 958 |
+
try:
|
| 959 |
+
module = sys.modules[func.__module__]
|
| 960 |
+
ffi = module._cffi_original_ffi
|
| 961 |
+
types_of_builtin_funcs = module._cffi_types_of_builtin_funcs
|
| 962 |
+
tp = types_of_builtin_funcs[func]
|
| 963 |
+
except (KeyError, AttributeError, TypeError):
|
| 964 |
+
return None
|
| 965 |
+
else:
|
| 966 |
+
with ffi._lock:
|
| 967 |
+
return ffi._get_cached_btype(tp)
|
data/tefig/envs/olmes-e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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ctypes, ctypes.util, operator, sys
|
| 2 |
+
from . import model
|
| 3 |
+
|
| 4 |
+
if sys.version_info < (3,):
|
| 5 |
+
bytechr = chr
|
| 6 |
+
else:
|
| 7 |
+
unicode = str
|
| 8 |
+
long = int
|
| 9 |
+
xrange = range
|
| 10 |
+
bytechr = lambda num: bytes([num])
|
| 11 |
+
|
| 12 |
+
class CTypesType(type):
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
class CTypesData(object):
|
| 16 |
+
__metaclass__ = CTypesType
|
| 17 |
+
__slots__ = ['__weakref__']
|
| 18 |
+
__name__ = '<cdata>'
|
| 19 |
+
|
| 20 |
+
def __init__(self, *args):
|
| 21 |
+
raise TypeError("cannot instantiate %r" % (self.__class__,))
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def _newp(cls, init):
|
| 25 |
+
raise TypeError("expected a pointer or array ctype, got '%s'"
|
| 26 |
+
% (cls._get_c_name(),))
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def _to_ctypes(value):
|
| 30 |
+
raise TypeError
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
def _arg_to_ctypes(cls, *value):
|
| 34 |
+
try:
|
| 35 |
+
ctype = cls._ctype
|
| 36 |
+
except AttributeError:
|
| 37 |
+
raise TypeError("cannot create an instance of %r" % (cls,))
|
| 38 |
+
if value:
|
| 39 |
+
res = cls._to_ctypes(*value)
|
| 40 |
+
if not isinstance(res, ctype):
|
| 41 |
+
res = cls._ctype(res)
|
| 42 |
+
else:
|
| 43 |
+
res = cls._ctype()
|
| 44 |
+
return res
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def _create_ctype_obj(cls, init):
|
| 48 |
+
if init is None:
|
| 49 |
+
return cls._arg_to_ctypes()
|
| 50 |
+
else:
|
| 51 |
+
return cls._arg_to_ctypes(init)
|
| 52 |
+
|
| 53 |
+
@staticmethod
|
| 54 |
+
def _from_ctypes(ctypes_value):
|
| 55 |
+
raise TypeError
|
| 56 |
+
|
| 57 |
+
@classmethod
|
| 58 |
+
def _get_c_name(cls, replace_with=''):
|
| 59 |
+
return cls._reftypename.replace(' &', replace_with)
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def _fix_class(cls):
|
| 63 |
+
cls.__name__ = 'CData<%s>' % (cls._get_c_name(),)
|
| 64 |
+
cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),)
|
| 65 |
+
cls.__module__ = 'ffi'
|
| 66 |
+
|
| 67 |
+
def _get_own_repr(self):
|
| 68 |
+
raise NotImplementedError
|
| 69 |
+
|
| 70 |
+
def _addr_repr(self, address):
|
| 71 |
+
if address == 0:
|
| 72 |
+
return 'NULL'
|
| 73 |
+
else:
|
| 74 |
+
if address < 0:
|
| 75 |
+
address += 1 << (8*ctypes.sizeof(ctypes.c_void_p))
|
| 76 |
+
return '0x%x' % address
|
| 77 |
+
|
| 78 |
+
def __repr__(self, c_name=None):
|
| 79 |
+
own = self._get_own_repr()
|
| 80 |
+
return '<cdata %r %s>' % (c_name or self._get_c_name(), own)
|
| 81 |
+
|
| 82 |
+
def _convert_to_address(self, BClass):
|
| 83 |
+
if BClass is None:
|
| 84 |
+
raise TypeError("cannot convert %r to an address" % (
|
| 85 |
+
self._get_c_name(),))
|
| 86 |
+
else:
|
| 87 |
+
raise TypeError("cannot convert %r to %r" % (
|
| 88 |
+
self._get_c_name(), BClass._get_c_name()))
|
| 89 |
+
|
| 90 |
+
@classmethod
|
| 91 |
+
def _get_size(cls):
|
| 92 |
+
return ctypes.sizeof(cls._ctype)
|
| 93 |
+
|
| 94 |
+
def _get_size_of_instance(self):
|
| 95 |
+
return ctypes.sizeof(self._ctype)
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
def _cast_from(cls, source):
|
| 99 |
+
raise TypeError("cannot cast to %r" % (cls._get_c_name(),))
|
| 100 |
+
|
| 101 |
+
def _cast_to_integer(self):
|
| 102 |
+
return self._convert_to_address(None)
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def _alignment(cls):
|
| 106 |
+
return ctypes.alignment(cls._ctype)
|
| 107 |
+
|
| 108 |
+
def __iter__(self):
|
| 109 |
+
raise TypeError("cdata %r does not support iteration" % (
|
| 110 |
+
self._get_c_name()),)
|
| 111 |
+
|
| 112 |
+
def _make_cmp(name):
|
| 113 |
+
cmpfunc = getattr(operator, name)
|
| 114 |
+
def cmp(self, other):
|
| 115 |
+
v_is_ptr = not isinstance(self, CTypesGenericPrimitive)
|
| 116 |
+
w_is_ptr = (isinstance(other, CTypesData) and
|
| 117 |
+
not isinstance(other, CTypesGenericPrimitive))
|
| 118 |
+
if v_is_ptr and w_is_ptr:
|
| 119 |
+
return cmpfunc(self._convert_to_address(None),
|
| 120 |
+
other._convert_to_address(None))
|
| 121 |
+
elif v_is_ptr or w_is_ptr:
|
| 122 |
+
return NotImplemented
|
| 123 |
+
else:
|
| 124 |
+
if isinstance(self, CTypesGenericPrimitive):
|
| 125 |
+
self = self._value
|
| 126 |
+
if isinstance(other, CTypesGenericPrimitive):
|
| 127 |
+
other = other._value
|
| 128 |
+
return cmpfunc(self, other)
|
| 129 |
+
cmp.func_name = name
|
| 130 |
+
return cmp
|
| 131 |
+
|
| 132 |
+
__eq__ = _make_cmp('__eq__')
|
| 133 |
+
__ne__ = _make_cmp('__ne__')
|
| 134 |
+
__lt__ = _make_cmp('__lt__')
|
| 135 |
+
__le__ = _make_cmp('__le__')
|
| 136 |
+
__gt__ = _make_cmp('__gt__')
|
| 137 |
+
__ge__ = _make_cmp('__ge__')
|
| 138 |
+
|
| 139 |
+
def __hash__(self):
|
| 140 |
+
return hash(self._convert_to_address(None))
|
| 141 |
+
|
| 142 |
+
def _to_string(self, maxlen):
|
| 143 |
+
raise TypeError("string(): %r" % (self,))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class CTypesGenericPrimitive(CTypesData):
|
| 147 |
+
__slots__ = []
|
| 148 |
+
|
| 149 |
+
def __hash__(self):
|
| 150 |
+
return hash(self._value)
|
| 151 |
+
|
| 152 |
+
def _get_own_repr(self):
|
| 153 |
+
return repr(self._from_ctypes(self._value))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class CTypesGenericArray(CTypesData):
|
| 157 |
+
__slots__ = []
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def _newp(cls, init):
|
| 161 |
+
return cls(init)
|
| 162 |
+
|
| 163 |
+
def __iter__(self):
|
| 164 |
+
for i in xrange(len(self)):
|
| 165 |
+
yield self[i]
|
| 166 |
+
|
| 167 |
+
def _get_own_repr(self):
|
| 168 |
+
return self._addr_repr(ctypes.addressof(self._blob))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class CTypesGenericPtr(CTypesData):
|
| 172 |
+
__slots__ = ['_address', '_as_ctype_ptr']
|
| 173 |
+
_automatic_casts = False
|
| 174 |
+
kind = "pointer"
|
| 175 |
+
|
| 176 |
+
@classmethod
|
| 177 |
+
def _newp(cls, init):
|
| 178 |
+
return cls(init)
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
def _cast_from(cls, source):
|
| 182 |
+
if source is None:
|
| 183 |
+
address = 0
|
| 184 |
+
elif isinstance(source, CTypesData):
|
| 185 |
+
address = source._cast_to_integer()
|
| 186 |
+
elif isinstance(source, (int, long)):
|
| 187 |
+
address = source
|
| 188 |
+
else:
|
| 189 |
+
raise TypeError("bad type for cast to %r: %r" %
|
| 190 |
+
(cls, type(source).__name__))
|
| 191 |
+
return cls._new_pointer_at(address)
|
| 192 |
+
|
| 193 |
+
@classmethod
|
| 194 |
+
def _new_pointer_at(cls, address):
|
| 195 |
+
self = cls.__new__(cls)
|
| 196 |
+
self._address = address
|
| 197 |
+
self._as_ctype_ptr = ctypes.cast(address, cls._ctype)
|
| 198 |
+
return self
|
| 199 |
+
|
| 200 |
+
def _get_own_repr(self):
|
| 201 |
+
try:
|
| 202 |
+
return self._addr_repr(self._address)
|
| 203 |
+
except AttributeError:
|
| 204 |
+
return '???'
|
| 205 |
+
|
| 206 |
+
def _cast_to_integer(self):
|
| 207 |
+
return self._address
|
| 208 |
+
|
| 209 |
+
def __nonzero__(self):
|
| 210 |
+
return bool(self._address)
|
| 211 |
+
__bool__ = __nonzero__
|
| 212 |
+
|
| 213 |
+
@classmethod
|
| 214 |
+
def _to_ctypes(cls, value):
|
| 215 |
+
if not isinstance(value, CTypesData):
|
| 216 |
+
raise TypeError("unexpected %s object" % type(value).__name__)
|
| 217 |
+
address = value._convert_to_address(cls)
|
| 218 |
+
return ctypes.cast(address, cls._ctype)
|
| 219 |
+
|
| 220 |
+
@classmethod
|
| 221 |
+
def _from_ctypes(cls, ctypes_ptr):
|
| 222 |
+
address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0
|
| 223 |
+
return cls._new_pointer_at(address)
|
| 224 |
+
|
| 225 |
+
@classmethod
|
| 226 |
+
def _initialize(cls, ctypes_ptr, value):
|
| 227 |
+
if value:
|
| 228 |
+
ctypes_ptr.contents = cls._to_ctypes(value).contents
|
| 229 |
+
|
| 230 |
+
def _convert_to_address(self, BClass):
|
| 231 |
+
if (BClass in (self.__class__, None) or BClass._automatic_casts
|
| 232 |
+
or self._automatic_casts):
|
| 233 |
+
return self._address
|
| 234 |
+
else:
|
| 235 |
+
return CTypesData._convert_to_address(self, BClass)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class CTypesBaseStructOrUnion(CTypesData):
|
| 239 |
+
__slots__ = ['_blob']
|
| 240 |
+
|
| 241 |
+
@classmethod
|
| 242 |
+
def _create_ctype_obj(cls, init):
|
| 243 |
+
# may be overridden
|
| 244 |
+
raise TypeError("cannot instantiate opaque type %s" % (cls,))
|
| 245 |
+
|
| 246 |
+
def _get_own_repr(self):
|
| 247 |
+
return self._addr_repr(ctypes.addressof(self._blob))
|
| 248 |
+
|
| 249 |
+
@classmethod
|
| 250 |
+
def _offsetof(cls, fieldname):
|
| 251 |
+
return getattr(cls._ctype, fieldname).offset
|
| 252 |
+
|
| 253 |
+
def _convert_to_address(self, BClass):
|
| 254 |
+
if getattr(BClass, '_BItem', None) is self.__class__:
|
| 255 |
+
return ctypes.addressof(self._blob)
|
| 256 |
+
else:
|
| 257 |
+
return CTypesData._convert_to_address(self, BClass)
|
| 258 |
+
|
| 259 |
+
@classmethod
|
| 260 |
+
def _from_ctypes(cls, ctypes_struct_or_union):
|
| 261 |
+
self = cls.__new__(cls)
|
| 262 |
+
self._blob = ctypes_struct_or_union
|
| 263 |
+
return self
|
| 264 |
+
|
| 265 |
+
@classmethod
|
| 266 |
+
def _to_ctypes(cls, value):
|
| 267 |
+
return value._blob
|
| 268 |
+
|
| 269 |
+
def __repr__(self, c_name=None):
|
| 270 |
+
return CTypesData.__repr__(self, c_name or self._get_c_name(' &'))
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class CTypesBackend(object):
|
| 274 |
+
|
| 275 |
+
PRIMITIVE_TYPES = {
|
| 276 |
+
'char': ctypes.c_char,
|
| 277 |
+
'short': ctypes.c_short,
|
| 278 |
+
'int': ctypes.c_int,
|
| 279 |
+
'long': ctypes.c_long,
|
| 280 |
+
'long long': ctypes.c_longlong,
|
| 281 |
+
'signed char': ctypes.c_byte,
|
| 282 |
+
'unsigned char': ctypes.c_ubyte,
|
| 283 |
+
'unsigned short': ctypes.c_ushort,
|
| 284 |
+
'unsigned int': ctypes.c_uint,
|
| 285 |
+
'unsigned long': ctypes.c_ulong,
|
| 286 |
+
'unsigned long long': ctypes.c_ulonglong,
|
| 287 |
+
'float': ctypes.c_float,
|
| 288 |
+
'double': ctypes.c_double,
|
| 289 |
+
'_Bool': ctypes.c_bool,
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
for _name in ['unsigned long long', 'unsigned long',
|
| 293 |
+
'unsigned int', 'unsigned short', 'unsigned char']:
|
| 294 |
+
_size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
|
| 295 |
+
PRIMITIVE_TYPES['uint%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
|
| 296 |
+
if _size == ctypes.sizeof(ctypes.c_void_p):
|
| 297 |
+
PRIMITIVE_TYPES['uintptr_t'] = PRIMITIVE_TYPES[_name]
|
| 298 |
+
if _size == ctypes.sizeof(ctypes.c_size_t):
|
| 299 |
+
PRIMITIVE_TYPES['size_t'] = PRIMITIVE_TYPES[_name]
|
| 300 |
+
|
| 301 |
+
for _name in ['long long', 'long', 'int', 'short', 'signed char']:
|
| 302 |
+
_size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
|
| 303 |
+
PRIMITIVE_TYPES['int%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
|
| 304 |
+
if _size == ctypes.sizeof(ctypes.c_void_p):
|
| 305 |
+
PRIMITIVE_TYPES['intptr_t'] = PRIMITIVE_TYPES[_name]
|
| 306 |
+
PRIMITIVE_TYPES['ptrdiff_t'] = PRIMITIVE_TYPES[_name]
|
| 307 |
+
if _size == ctypes.sizeof(ctypes.c_size_t):
|
| 308 |
+
PRIMITIVE_TYPES['ssize_t'] = PRIMITIVE_TYPES[_name]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def __init__(self):
|
| 312 |
+
self.RTLD_LAZY = 0 # not supported anyway by ctypes
|
| 313 |
+
self.RTLD_NOW = 0
|
| 314 |
+
self.RTLD_GLOBAL = ctypes.RTLD_GLOBAL
|
| 315 |
+
self.RTLD_LOCAL = ctypes.RTLD_LOCAL
|
| 316 |
+
|
| 317 |
+
def set_ffi(self, ffi):
|
| 318 |
+
self.ffi = ffi
|
| 319 |
+
|
| 320 |
+
def _get_types(self):
|
| 321 |
+
return CTypesData, CTypesType
|
| 322 |
+
|
| 323 |
+
def load_library(self, path, flags=0):
|
| 324 |
+
cdll = ctypes.CDLL(path, flags)
|
| 325 |
+
return CTypesLibrary(self, cdll)
|
| 326 |
+
|
| 327 |
+
def new_void_type(self):
|
| 328 |
+
class CTypesVoid(CTypesData):
|
| 329 |
+
__slots__ = []
|
| 330 |
+
_reftypename = 'void &'
|
| 331 |
+
@staticmethod
|
| 332 |
+
def _from_ctypes(novalue):
|
| 333 |
+
return None
|
| 334 |
+
@staticmethod
|
| 335 |
+
def _to_ctypes(novalue):
|
| 336 |
+
if novalue is not None:
|
| 337 |
+
raise TypeError("None expected, got %s object" %
|
| 338 |
+
(type(novalue).__name__,))
|
| 339 |
+
return None
|
| 340 |
+
CTypesVoid._fix_class()
|
| 341 |
+
return CTypesVoid
|
| 342 |
+
|
| 343 |
+
def new_primitive_type(self, name):
|
| 344 |
+
if name == 'wchar_t':
|
| 345 |
+
raise NotImplementedError(name)
|
| 346 |
+
ctype = self.PRIMITIVE_TYPES[name]
|
| 347 |
+
if name == 'char':
|
| 348 |
+
kind = 'char'
|
| 349 |
+
elif name in ('float', 'double'):
|
| 350 |
+
kind = 'float'
|
| 351 |
+
else:
|
| 352 |
+
if name in ('signed char', 'unsigned char'):
|
| 353 |
+
kind = 'byte'
|
| 354 |
+
elif name == '_Bool':
|
| 355 |
+
kind = 'bool'
|
| 356 |
+
else:
|
| 357 |
+
kind = 'int'
|
| 358 |
+
is_signed = (ctype(-1).value == -1)
|
| 359 |
+
#
|
| 360 |
+
def _cast_source_to_int(source):
|
| 361 |
+
if isinstance(source, (int, long, float)):
|
| 362 |
+
source = int(source)
|
| 363 |
+
elif isinstance(source, CTypesData):
|
| 364 |
+
source = source._cast_to_integer()
|
| 365 |
+
elif isinstance(source, bytes):
|
| 366 |
+
source = ord(source)
|
| 367 |
+
elif source is None:
|
| 368 |
+
source = 0
|
| 369 |
+
else:
|
| 370 |
+
raise TypeError("bad type for cast to %r: %r" %
|
| 371 |
+
(CTypesPrimitive, type(source).__name__))
|
| 372 |
+
return source
|
| 373 |
+
#
|
| 374 |
+
kind1 = kind
|
| 375 |
+
class CTypesPrimitive(CTypesGenericPrimitive):
|
| 376 |
+
__slots__ = ['_value']
|
| 377 |
+
_ctype = ctype
|
| 378 |
+
_reftypename = '%s &' % name
|
| 379 |
+
kind = kind1
|
| 380 |
+
|
| 381 |
+
def __init__(self, value):
|
| 382 |
+
self._value = value
|
| 383 |
+
|
| 384 |
+
@staticmethod
|
| 385 |
+
def _create_ctype_obj(init):
|
| 386 |
+
if init is None:
|
| 387 |
+
return ctype()
|
| 388 |
+
return ctype(CTypesPrimitive._to_ctypes(init))
|
| 389 |
+
|
| 390 |
+
if kind == 'int' or kind == 'byte':
|
| 391 |
+
@classmethod
|
| 392 |
+
def _cast_from(cls, source):
|
| 393 |
+
source = _cast_source_to_int(source)
|
| 394 |
+
source = ctype(source).value # cast within range
|
| 395 |
+
return cls(source)
|
| 396 |
+
def __int__(self):
|
| 397 |
+
return self._value
|
| 398 |
+
|
| 399 |
+
if kind == 'bool':
|
| 400 |
+
@classmethod
|
| 401 |
+
def _cast_from(cls, source):
|
| 402 |
+
if not isinstance(source, (int, long, float)):
|
| 403 |
+
source = _cast_source_to_int(source)
|
| 404 |
+
return cls(bool(source))
|
| 405 |
+
def __int__(self):
|
| 406 |
+
return int(self._value)
|
| 407 |
+
|
| 408 |
+
if kind == 'char':
|
| 409 |
+
@classmethod
|
| 410 |
+
def _cast_from(cls, source):
|
| 411 |
+
source = _cast_source_to_int(source)
|
| 412 |
+
source = bytechr(source & 0xFF)
|
| 413 |
+
return cls(source)
|
| 414 |
+
def __int__(self):
|
| 415 |
+
return ord(self._value)
|
| 416 |
+
|
| 417 |
+
if kind == 'float':
|
| 418 |
+
@classmethod
|
| 419 |
+
def _cast_from(cls, source):
|
| 420 |
+
if isinstance(source, float):
|
| 421 |
+
pass
|
| 422 |
+
elif isinstance(source, CTypesGenericPrimitive):
|
| 423 |
+
if hasattr(source, '__float__'):
|
| 424 |
+
source = float(source)
|
| 425 |
+
else:
|
| 426 |
+
source = int(source)
|
| 427 |
+
else:
|
| 428 |
+
source = _cast_source_to_int(source)
|
| 429 |
+
source = ctype(source).value # fix precision
|
| 430 |
+
return cls(source)
|
| 431 |
+
def __int__(self):
|
| 432 |
+
return int(self._value)
|
| 433 |
+
def __float__(self):
|
| 434 |
+
return self._value
|
| 435 |
+
|
| 436 |
+
_cast_to_integer = __int__
|
| 437 |
+
|
| 438 |
+
if kind == 'int' or kind == 'byte' or kind == 'bool':
|
| 439 |
+
@staticmethod
|
| 440 |
+
def _to_ctypes(x):
|
| 441 |
+
if not isinstance(x, (int, long)):
|
| 442 |
+
if isinstance(x, CTypesData):
|
| 443 |
+
x = int(x)
|
| 444 |
+
else:
|
| 445 |
+
raise TypeError("integer expected, got %s" %
|
| 446 |
+
type(x).__name__)
|
| 447 |
+
if ctype(x).value != x:
|
| 448 |
+
if not is_signed and x < 0:
|
| 449 |
+
raise OverflowError("%s: negative integer" % name)
|
| 450 |
+
else:
|
| 451 |
+
raise OverflowError("%s: integer out of bounds"
|
| 452 |
+
% name)
|
| 453 |
+
return x
|
| 454 |
+
|
| 455 |
+
if kind == 'char':
|
| 456 |
+
@staticmethod
|
| 457 |
+
def _to_ctypes(x):
|
| 458 |
+
if isinstance(x, bytes) and len(x) == 1:
|
| 459 |
+
return x
|
| 460 |
+
if isinstance(x, CTypesPrimitive): # <CData <char>>
|
| 461 |
+
return x._value
|
| 462 |
+
raise TypeError("character expected, got %s" %
|
| 463 |
+
type(x).__name__)
|
| 464 |
+
def __nonzero__(self):
|
| 465 |
+
return ord(self._value) != 0
|
| 466 |
+
else:
|
| 467 |
+
def __nonzero__(self):
|
| 468 |
+
return self._value != 0
|
| 469 |
+
__bool__ = __nonzero__
|
| 470 |
+
|
| 471 |
+
if kind == 'float':
|
| 472 |
+
@staticmethod
|
| 473 |
+
def _to_ctypes(x):
|
| 474 |
+
if not isinstance(x, (int, long, float, CTypesData)):
|
| 475 |
+
raise TypeError("float expected, got %s" %
|
| 476 |
+
type(x).__name__)
|
| 477 |
+
return ctype(x).value
|
| 478 |
+
|
| 479 |
+
@staticmethod
|
| 480 |
+
def _from_ctypes(value):
|
| 481 |
+
return getattr(value, 'value', value)
|
| 482 |
+
|
| 483 |
+
@staticmethod
|
| 484 |
+
def _initialize(blob, init):
|
| 485 |
+
blob.value = CTypesPrimitive._to_ctypes(init)
|
| 486 |
+
|
| 487 |
+
if kind == 'char':
|
| 488 |
+
def _to_string(self, maxlen):
|
| 489 |
+
return self._value
|
| 490 |
+
if kind == 'byte':
|
| 491 |
+
def _to_string(self, maxlen):
|
| 492 |
+
return chr(self._value & 0xff)
|
| 493 |
+
#
|
| 494 |
+
CTypesPrimitive._fix_class()
|
| 495 |
+
return CTypesPrimitive
|
| 496 |
+
|
| 497 |
+
def new_pointer_type(self, BItem):
|
| 498 |
+
getbtype = self.ffi._get_cached_btype
|
| 499 |
+
if BItem is getbtype(model.PrimitiveType('char')):
|
| 500 |
+
kind = 'charp'
|
| 501 |
+
elif BItem in (getbtype(model.PrimitiveType('signed char')),
|
| 502 |
+
getbtype(model.PrimitiveType('unsigned char'))):
|
| 503 |
+
kind = 'bytep'
|
| 504 |
+
elif BItem is getbtype(model.void_type):
|
| 505 |
+
kind = 'voidp'
|
| 506 |
+
else:
|
| 507 |
+
kind = 'generic'
|
| 508 |
+
#
|
| 509 |
+
class CTypesPtr(CTypesGenericPtr):
|
| 510 |
+
__slots__ = ['_own']
|
| 511 |
+
if kind == 'charp':
|
| 512 |
+
__slots__ += ['__as_strbuf']
|
| 513 |
+
_BItem = BItem
|
| 514 |
+
if hasattr(BItem, '_ctype'):
|
| 515 |
+
_ctype = ctypes.POINTER(BItem._ctype)
|
| 516 |
+
_bitem_size = ctypes.sizeof(BItem._ctype)
|
| 517 |
+
else:
|
| 518 |
+
_ctype = ctypes.c_void_p
|
| 519 |
+
if issubclass(BItem, CTypesGenericArray):
|
| 520 |
+
_reftypename = BItem._get_c_name('(* &)')
|
| 521 |
+
else:
|
| 522 |
+
_reftypename = BItem._get_c_name(' * &')
|
| 523 |
+
|
| 524 |
+
def __init__(self, init):
|
| 525 |
+
ctypeobj = BItem._create_ctype_obj(init)
|
| 526 |
+
if kind == 'charp':
|
| 527 |
+
self.__as_strbuf = ctypes.create_string_buffer(
|
| 528 |
+
ctypeobj.value + b'\x00')
|
| 529 |
+
self._as_ctype_ptr = ctypes.cast(
|
| 530 |
+
self.__as_strbuf, self._ctype)
|
| 531 |
+
else:
|
| 532 |
+
self._as_ctype_ptr = ctypes.pointer(ctypeobj)
|
| 533 |
+
self._address = ctypes.cast(self._as_ctype_ptr,
|
| 534 |
+
ctypes.c_void_p).value
|
| 535 |
+
self._own = True
|
| 536 |
+
|
| 537 |
+
def __add__(self, other):
|
| 538 |
+
if isinstance(other, (int, long)):
|
| 539 |
+
return self._new_pointer_at(self._address +
|
| 540 |
+
other * self._bitem_size)
|
| 541 |
+
else:
|
| 542 |
+
return NotImplemented
|
| 543 |
+
|
| 544 |
+
def __sub__(self, other):
|
| 545 |
+
if isinstance(other, (int, long)):
|
| 546 |
+
return self._new_pointer_at(self._address -
|
| 547 |
+
other * self._bitem_size)
|
| 548 |
+
elif type(self) is type(other):
|
| 549 |
+
return (self._address - other._address) // self._bitem_size
|
| 550 |
+
else:
|
| 551 |
+
return NotImplemented
|
| 552 |
+
|
| 553 |
+
def __getitem__(self, index):
|
| 554 |
+
if getattr(self, '_own', False) and index != 0:
|
| 555 |
+
raise IndexError
|
| 556 |
+
return BItem._from_ctypes(self._as_ctype_ptr[index])
|
| 557 |
+
|
| 558 |
+
def __setitem__(self, index, value):
|
| 559 |
+
self._as_ctype_ptr[index] = BItem._to_ctypes(value)
|
| 560 |
+
|
| 561 |
+
if kind == 'charp' or kind == 'voidp':
|
| 562 |
+
@classmethod
|
| 563 |
+
def _arg_to_ctypes(cls, *value):
|
| 564 |
+
if value and isinstance(value[0], bytes):
|
| 565 |
+
return ctypes.c_char_p(value[0])
|
| 566 |
+
else:
|
| 567 |
+
return super(CTypesPtr, cls)._arg_to_ctypes(*value)
|
| 568 |
+
|
| 569 |
+
if kind == 'charp' or kind == 'bytep':
|
| 570 |
+
def _to_string(self, maxlen):
|
| 571 |
+
if maxlen < 0:
|
| 572 |
+
maxlen = sys.maxsize
|
| 573 |
+
p = ctypes.cast(self._as_ctype_ptr,
|
| 574 |
+
ctypes.POINTER(ctypes.c_char))
|
| 575 |
+
n = 0
|
| 576 |
+
while n < maxlen and p[n] != b'\x00':
|
| 577 |
+
n += 1
|
| 578 |
+
return b''.join([p[i] for i in range(n)])
|
| 579 |
+
|
| 580 |
+
def _get_own_repr(self):
|
| 581 |
+
if getattr(self, '_own', False):
|
| 582 |
+
return 'owning %d bytes' % (
|
| 583 |
+
ctypes.sizeof(self._as_ctype_ptr.contents),)
|
| 584 |
+
return super(CTypesPtr, self)._get_own_repr()
|
| 585 |
+
#
|
| 586 |
+
if (BItem is self.ffi._get_cached_btype(model.void_type) or
|
| 587 |
+
BItem is self.ffi._get_cached_btype(model.PrimitiveType('char'))):
|
| 588 |
+
CTypesPtr._automatic_casts = True
|
| 589 |
+
#
|
| 590 |
+
CTypesPtr._fix_class()
|
| 591 |
+
return CTypesPtr
|
| 592 |
+
|
| 593 |
+
def new_array_type(self, CTypesPtr, length):
|
| 594 |
+
if length is None:
|
| 595 |
+
brackets = ' &[]'
|
| 596 |
+
else:
|
| 597 |
+
brackets = ' &[%d]' % length
|
| 598 |
+
BItem = CTypesPtr._BItem
|
| 599 |
+
getbtype = self.ffi._get_cached_btype
|
| 600 |
+
if BItem is getbtype(model.PrimitiveType('char')):
|
| 601 |
+
kind = 'char'
|
| 602 |
+
elif BItem in (getbtype(model.PrimitiveType('signed char')),
|
| 603 |
+
getbtype(model.PrimitiveType('unsigned char'))):
|
| 604 |
+
kind = 'byte'
|
| 605 |
+
else:
|
| 606 |
+
kind = 'generic'
|
| 607 |
+
#
|
| 608 |
+
class CTypesArray(CTypesGenericArray):
|
| 609 |
+
__slots__ = ['_blob', '_own']
|
| 610 |
+
if length is not None:
|
| 611 |
+
_ctype = BItem._ctype * length
|
| 612 |
+
else:
|
| 613 |
+
__slots__.append('_ctype')
|
| 614 |
+
_reftypename = BItem._get_c_name(brackets)
|
| 615 |
+
_declared_length = length
|
| 616 |
+
_CTPtr = CTypesPtr
|
| 617 |
+
|
| 618 |
+
def __init__(self, init):
|
| 619 |
+
if length is None:
|
| 620 |
+
if isinstance(init, (int, long)):
|
| 621 |
+
len1 = init
|
| 622 |
+
init = None
|
| 623 |
+
elif kind == 'char' and isinstance(init, bytes):
|
| 624 |
+
len1 = len(init) + 1 # extra null
|
| 625 |
+
else:
|
| 626 |
+
init = tuple(init)
|
| 627 |
+
len1 = len(init)
|
| 628 |
+
self._ctype = BItem._ctype * len1
|
| 629 |
+
self._blob = self._ctype()
|
| 630 |
+
self._own = True
|
| 631 |
+
if init is not None:
|
| 632 |
+
self._initialize(self._blob, init)
|
| 633 |
+
|
| 634 |
+
@staticmethod
|
| 635 |
+
def _initialize(blob, init):
|
| 636 |
+
if isinstance(init, bytes):
|
| 637 |
+
init = [init[i:i+1] for i in range(len(init))]
|
| 638 |
+
else:
|
| 639 |
+
if isinstance(init, CTypesGenericArray):
|
| 640 |
+
if (len(init) != len(blob) or
|
| 641 |
+
not isinstance(init, CTypesArray)):
|
| 642 |
+
raise TypeError("length/type mismatch: %s" % (init,))
|
| 643 |
+
init = tuple(init)
|
| 644 |
+
if len(init) > len(blob):
|
| 645 |
+
raise IndexError("too many initializers")
|
| 646 |
+
addr = ctypes.cast(blob, ctypes.c_void_p).value
|
| 647 |
+
PTR = ctypes.POINTER(BItem._ctype)
|
| 648 |
+
itemsize = ctypes.sizeof(BItem._ctype)
|
| 649 |
+
for i, value in enumerate(init):
|
| 650 |
+
p = ctypes.cast(addr + i * itemsize, PTR)
|
| 651 |
+
BItem._initialize(p.contents, value)
|
| 652 |
+
|
| 653 |
+
def __len__(self):
|
| 654 |
+
return len(self._blob)
|
| 655 |
+
|
| 656 |
+
def __getitem__(self, index):
|
| 657 |
+
if not (0 <= index < len(self._blob)):
|
| 658 |
+
raise IndexError
|
| 659 |
+
return BItem._from_ctypes(self._blob[index])
|
| 660 |
+
|
| 661 |
+
def __setitem__(self, index, value):
|
| 662 |
+
if not (0 <= index < len(self._blob)):
|
| 663 |
+
raise IndexError
|
| 664 |
+
self._blob[index] = BItem._to_ctypes(value)
|
| 665 |
+
|
| 666 |
+
if kind == 'char' or kind == 'byte':
|
| 667 |
+
def _to_string(self, maxlen):
|
| 668 |
+
if maxlen < 0:
|
| 669 |
+
maxlen = len(self._blob)
|
| 670 |
+
p = ctypes.cast(self._blob,
|
| 671 |
+
ctypes.POINTER(ctypes.c_char))
|
| 672 |
+
n = 0
|
| 673 |
+
while n < maxlen and p[n] != b'\x00':
|
| 674 |
+
n += 1
|
| 675 |
+
return b''.join([p[i] for i in range(n)])
|
| 676 |
+
|
| 677 |
+
def _get_own_repr(self):
|
| 678 |
+
if getattr(self, '_own', False):
|
| 679 |
+
return 'owning %d bytes' % (ctypes.sizeof(self._blob),)
|
| 680 |
+
return super(CTypesArray, self)._get_own_repr()
|
| 681 |
+
|
| 682 |
+
def _convert_to_address(self, BClass):
|
| 683 |
+
if BClass in (CTypesPtr, None) or BClass._automatic_casts:
|
| 684 |
+
return ctypes.addressof(self._blob)
|
| 685 |
+
else:
|
| 686 |
+
return CTypesData._convert_to_address(self, BClass)
|
| 687 |
+
|
| 688 |
+
@staticmethod
|
| 689 |
+
def _from_ctypes(ctypes_array):
|
| 690 |
+
self = CTypesArray.__new__(CTypesArray)
|
| 691 |
+
self._blob = ctypes_array
|
| 692 |
+
return self
|
| 693 |
+
|
| 694 |
+
@staticmethod
|
| 695 |
+
def _arg_to_ctypes(value):
|
| 696 |
+
return CTypesPtr._arg_to_ctypes(value)
|
| 697 |
+
|
| 698 |
+
def __add__(self, other):
|
| 699 |
+
if isinstance(other, (int, long)):
|
| 700 |
+
return CTypesPtr._new_pointer_at(
|
| 701 |
+
ctypes.addressof(self._blob) +
|
| 702 |
+
other * ctypes.sizeof(BItem._ctype))
|
| 703 |
+
else:
|
| 704 |
+
return NotImplemented
|
| 705 |
+
|
| 706 |
+
@classmethod
|
| 707 |
+
def _cast_from(cls, source):
|
| 708 |
+
raise NotImplementedError("casting to %r" % (
|
| 709 |
+
cls._get_c_name(),))
|
| 710 |
+
#
|
| 711 |
+
CTypesArray._fix_class()
|
| 712 |
+
return CTypesArray
|
| 713 |
+
|
| 714 |
+
def _new_struct_or_union(self, kind, name, base_ctypes_class):
|
| 715 |
+
#
|
| 716 |
+
class struct_or_union(base_ctypes_class):
|
| 717 |
+
pass
|
| 718 |
+
struct_or_union.__name__ = '%s_%s' % (kind, name)
|
| 719 |
+
kind1 = kind
|
| 720 |
+
#
|
| 721 |
+
class CTypesStructOrUnion(CTypesBaseStructOrUnion):
|
| 722 |
+
__slots__ = ['_blob']
|
| 723 |
+
_ctype = struct_or_union
|
| 724 |
+
_reftypename = '%s &' % (name,)
|
| 725 |
+
_kind = kind = kind1
|
| 726 |
+
#
|
| 727 |
+
CTypesStructOrUnion._fix_class()
|
| 728 |
+
return CTypesStructOrUnion
|
| 729 |
+
|
| 730 |
+
def new_struct_type(self, name):
|
| 731 |
+
return self._new_struct_or_union('struct', name, ctypes.Structure)
|
| 732 |
+
|
| 733 |
+
def new_union_type(self, name):
|
| 734 |
+
return self._new_struct_or_union('union', name, ctypes.Union)
|
| 735 |
+
|
| 736 |
+
def complete_struct_or_union(self, CTypesStructOrUnion, fields, tp,
|
| 737 |
+
totalsize=-1, totalalignment=-1, sflags=0,
|
| 738 |
+
pack=0):
|
| 739 |
+
if totalsize >= 0 or totalalignment >= 0:
|
| 740 |
+
raise NotImplementedError("the ctypes backend of CFFI does not support "
|
| 741 |
+
"structures completed by verify(); please "
|
| 742 |
+
"compile and install the _cffi_backend module.")
|
| 743 |
+
struct_or_union = CTypesStructOrUnion._ctype
|
| 744 |
+
fnames = [fname for (fname, BField, bitsize) in fields]
|
| 745 |
+
btypes = [BField for (fname, BField, bitsize) in fields]
|
| 746 |
+
bitfields = [bitsize for (fname, BField, bitsize) in fields]
|
| 747 |
+
#
|
| 748 |
+
bfield_types = {}
|
| 749 |
+
cfields = []
|
| 750 |
+
for (fname, BField, bitsize) in fields:
|
| 751 |
+
if bitsize < 0:
|
| 752 |
+
cfields.append((fname, BField._ctype))
|
| 753 |
+
bfield_types[fname] = BField
|
| 754 |
+
else:
|
| 755 |
+
cfields.append((fname, BField._ctype, bitsize))
|
| 756 |
+
bfield_types[fname] = Ellipsis
|
| 757 |
+
if sflags & 8:
|
| 758 |
+
struct_or_union._pack_ = 1
|
| 759 |
+
elif pack:
|
| 760 |
+
struct_or_union._pack_ = pack
|
| 761 |
+
struct_or_union._fields_ = cfields
|
| 762 |
+
CTypesStructOrUnion._bfield_types = bfield_types
|
| 763 |
+
#
|
| 764 |
+
@staticmethod
|
| 765 |
+
def _create_ctype_obj(init):
|
| 766 |
+
result = struct_or_union()
|
| 767 |
+
if init is not None:
|
| 768 |
+
initialize(result, init)
|
| 769 |
+
return result
|
| 770 |
+
CTypesStructOrUnion._create_ctype_obj = _create_ctype_obj
|
| 771 |
+
#
|
| 772 |
+
def initialize(blob, init):
|
| 773 |
+
if is_union:
|
| 774 |
+
if len(init) > 1:
|
| 775 |
+
raise ValueError("union initializer: %d items given, but "
|
| 776 |
+
"only one supported (use a dict if needed)"
|
| 777 |
+
% (len(init),))
|
| 778 |
+
if not isinstance(init, dict):
|
| 779 |
+
if isinstance(init, (bytes, unicode)):
|
| 780 |
+
raise TypeError("union initializer: got a str")
|
| 781 |
+
init = tuple(init)
|
| 782 |
+
if len(init) > len(fnames):
|
| 783 |
+
raise ValueError("too many values for %s initializer" %
|
| 784 |
+
CTypesStructOrUnion._get_c_name())
|
| 785 |
+
init = dict(zip(fnames, init))
|
| 786 |
+
addr = ctypes.addressof(blob)
|
| 787 |
+
for fname, value in init.items():
|
| 788 |
+
BField, bitsize = name2fieldtype[fname]
|
| 789 |
+
assert bitsize < 0, \
|
| 790 |
+
"not implemented: initializer with bit fields"
|
| 791 |
+
offset = CTypesStructOrUnion._offsetof(fname)
|
| 792 |
+
PTR = ctypes.POINTER(BField._ctype)
|
| 793 |
+
p = ctypes.cast(addr + offset, PTR)
|
| 794 |
+
BField._initialize(p.contents, value)
|
| 795 |
+
is_union = CTypesStructOrUnion._kind == 'union'
|
| 796 |
+
name2fieldtype = dict(zip(fnames, zip(btypes, bitfields)))
|
| 797 |
+
#
|
| 798 |
+
for fname, BField, bitsize in fields:
|
| 799 |
+
if fname == '':
|
| 800 |
+
raise NotImplementedError("nested anonymous structs/unions")
|
| 801 |
+
if hasattr(CTypesStructOrUnion, fname):
|
| 802 |
+
raise ValueError("the field name %r conflicts in "
|
| 803 |
+
"the ctypes backend" % fname)
|
| 804 |
+
if bitsize < 0:
|
| 805 |
+
def getter(self, fname=fname, BField=BField,
|
| 806 |
+
offset=CTypesStructOrUnion._offsetof(fname),
|
| 807 |
+
PTR=ctypes.POINTER(BField._ctype)):
|
| 808 |
+
addr = ctypes.addressof(self._blob)
|
| 809 |
+
p = ctypes.cast(addr + offset, PTR)
|
| 810 |
+
return BField._from_ctypes(p.contents)
|
| 811 |
+
def setter(self, value, fname=fname, BField=BField):
|
| 812 |
+
setattr(self._blob, fname, BField._to_ctypes(value))
|
| 813 |
+
#
|
| 814 |
+
if issubclass(BField, CTypesGenericArray):
|
| 815 |
+
setter = None
|
| 816 |
+
if BField._declared_length == 0:
|
| 817 |
+
def getter(self, fname=fname, BFieldPtr=BField._CTPtr,
|
| 818 |
+
offset=CTypesStructOrUnion._offsetof(fname),
|
| 819 |
+
PTR=ctypes.POINTER(BField._ctype)):
|
| 820 |
+
addr = ctypes.addressof(self._blob)
|
| 821 |
+
p = ctypes.cast(addr + offset, PTR)
|
| 822 |
+
return BFieldPtr._from_ctypes(p)
|
| 823 |
+
#
|
| 824 |
+
else:
|
| 825 |
+
def getter(self, fname=fname, BField=BField):
|
| 826 |
+
return BField._from_ctypes(getattr(self._blob, fname))
|
| 827 |
+
def setter(self, value, fname=fname, BField=BField):
|
| 828 |
+
# xxx obscure workaround
|
| 829 |
+
value = BField._to_ctypes(value)
|
| 830 |
+
oldvalue = getattr(self._blob, fname)
|
| 831 |
+
setattr(self._blob, fname, value)
|
| 832 |
+
if value != getattr(self._blob, fname):
|
| 833 |
+
setattr(self._blob, fname, oldvalue)
|
| 834 |
+
raise OverflowError("value too large for bitfield")
|
| 835 |
+
setattr(CTypesStructOrUnion, fname, property(getter, setter))
|
| 836 |
+
#
|
| 837 |
+
CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp))
|
| 838 |
+
for fname in fnames:
|
| 839 |
+
if hasattr(CTypesPtr, fname):
|
| 840 |
+
raise ValueError("the field name %r conflicts in "
|
| 841 |
+
"the ctypes backend" % fname)
|
| 842 |
+
def getter(self, fname=fname):
|
| 843 |
+
return getattr(self[0], fname)
|
| 844 |
+
def setter(self, value, fname=fname):
|
| 845 |
+
setattr(self[0], fname, value)
|
| 846 |
+
setattr(CTypesPtr, fname, property(getter, setter))
|
| 847 |
+
|
| 848 |
+
def new_function_type(self, BArgs, BResult, has_varargs):
|
| 849 |
+
nameargs = [BArg._get_c_name() for BArg in BArgs]
|
| 850 |
+
if has_varargs:
|
| 851 |
+
nameargs.append('...')
|
| 852 |
+
nameargs = ', '.join(nameargs)
|
| 853 |
+
#
|
| 854 |
+
class CTypesFunctionPtr(CTypesGenericPtr):
|
| 855 |
+
__slots__ = ['_own_callback', '_name']
|
| 856 |
+
_ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None),
|
| 857 |
+
*[BArg._ctype for BArg in BArgs],
|
| 858 |
+
use_errno=True)
|
| 859 |
+
_reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,))
|
| 860 |
+
|
| 861 |
+
def __init__(self, init, error=None):
|
| 862 |
+
# create a callback to the Python callable init()
|
| 863 |
+
import traceback
|
| 864 |
+
assert not has_varargs, "varargs not supported for callbacks"
|
| 865 |
+
if getattr(BResult, '_ctype', None) is not None:
|
| 866 |
+
error = BResult._from_ctypes(
|
| 867 |
+
BResult._create_ctype_obj(error))
|
| 868 |
+
else:
|
| 869 |
+
error = None
|
| 870 |
+
def callback(*args):
|
| 871 |
+
args2 = []
|
| 872 |
+
for arg, BArg in zip(args, BArgs):
|
| 873 |
+
args2.append(BArg._from_ctypes(arg))
|
| 874 |
+
try:
|
| 875 |
+
res2 = init(*args2)
|
| 876 |
+
res2 = BResult._to_ctypes(res2)
|
| 877 |
+
except:
|
| 878 |
+
traceback.print_exc()
|
| 879 |
+
res2 = error
|
| 880 |
+
if issubclass(BResult, CTypesGenericPtr):
|
| 881 |
+
if res2:
|
| 882 |
+
res2 = ctypes.cast(res2, ctypes.c_void_p).value
|
| 883 |
+
# .value: http://bugs.python.org/issue1574593
|
| 884 |
+
else:
|
| 885 |
+
res2 = None
|
| 886 |
+
#print repr(res2)
|
| 887 |
+
return res2
|
| 888 |
+
if issubclass(BResult, CTypesGenericPtr):
|
| 889 |
+
# The only pointers callbacks can return are void*s:
|
| 890 |
+
# http://bugs.python.org/issue5710
|
| 891 |
+
callback_ctype = ctypes.CFUNCTYPE(
|
| 892 |
+
ctypes.c_void_p,
|
| 893 |
+
*[BArg._ctype for BArg in BArgs],
|
| 894 |
+
use_errno=True)
|
| 895 |
+
else:
|
| 896 |
+
callback_ctype = CTypesFunctionPtr._ctype
|
| 897 |
+
self._as_ctype_ptr = callback_ctype(callback)
|
| 898 |
+
self._address = ctypes.cast(self._as_ctype_ptr,
|
| 899 |
+
ctypes.c_void_p).value
|
| 900 |
+
self._own_callback = init
|
| 901 |
+
|
| 902 |
+
@staticmethod
|
| 903 |
+
def _initialize(ctypes_ptr, value):
|
| 904 |
+
if value:
|
| 905 |
+
raise NotImplementedError("ctypes backend: not supported: "
|
| 906 |
+
"initializers for function pointers")
|
| 907 |
+
|
| 908 |
+
def __repr__(self):
|
| 909 |
+
c_name = getattr(self, '_name', None)
|
| 910 |
+
if c_name:
|
| 911 |
+
i = self._reftypename.index('(* &)')
|
| 912 |
+
if self._reftypename[i-1] not in ' )*':
|
| 913 |
+
c_name = ' ' + c_name
|
| 914 |
+
c_name = self._reftypename.replace('(* &)', c_name)
|
| 915 |
+
return CTypesData.__repr__(self, c_name)
|
| 916 |
+
|
| 917 |
+
def _get_own_repr(self):
|
| 918 |
+
if getattr(self, '_own_callback', None) is not None:
|
| 919 |
+
return 'calling %r' % (self._own_callback,)
|
| 920 |
+
return super(CTypesFunctionPtr, self)._get_own_repr()
|
| 921 |
+
|
| 922 |
+
def __call__(self, *args):
|
| 923 |
+
if has_varargs:
|
| 924 |
+
assert len(args) >= len(BArgs)
|
| 925 |
+
extraargs = args[len(BArgs):]
|
| 926 |
+
args = args[:len(BArgs)]
|
| 927 |
+
else:
|
| 928 |
+
assert len(args) == len(BArgs)
|
| 929 |
+
ctypes_args = []
|
| 930 |
+
for arg, BArg in zip(args, BArgs):
|
| 931 |
+
ctypes_args.append(BArg._arg_to_ctypes(arg))
|
| 932 |
+
if has_varargs:
|
| 933 |
+
for i, arg in enumerate(extraargs):
|
| 934 |
+
if arg is None:
|
| 935 |
+
ctypes_args.append(ctypes.c_void_p(0)) # NULL
|
| 936 |
+
continue
|
| 937 |
+
if not isinstance(arg, CTypesData):
|
| 938 |
+
raise TypeError(
|
| 939 |
+
"argument %d passed in the variadic part "
|
| 940 |
+
"needs to be a cdata object (got %s)" %
|
| 941 |
+
(1 + len(BArgs) + i, type(arg).__name__))
|
| 942 |
+
ctypes_args.append(arg._arg_to_ctypes(arg))
|
| 943 |
+
result = self._as_ctype_ptr(*ctypes_args)
|
| 944 |
+
return BResult._from_ctypes(result)
|
| 945 |
+
#
|
| 946 |
+
CTypesFunctionPtr._fix_class()
|
| 947 |
+
return CTypesFunctionPtr
|
| 948 |
+
|
| 949 |
+
def new_enum_type(self, name, enumerators, enumvalues, CTypesInt):
|
| 950 |
+
assert isinstance(name, str)
|
| 951 |
+
reverse_mapping = dict(zip(reversed(enumvalues),
|
| 952 |
+
reversed(enumerators)))
|
| 953 |
+
#
|
| 954 |
+
class CTypesEnum(CTypesInt):
|
| 955 |
+
__slots__ = []
|
| 956 |
+
_reftypename = '%s &' % name
|
| 957 |
+
|
| 958 |
+
def _get_own_repr(self):
|
| 959 |
+
value = self._value
|
| 960 |
+
try:
|
| 961 |
+
return '%d: %s' % (value, reverse_mapping[value])
|
| 962 |
+
except KeyError:
|
| 963 |
+
return str(value)
|
| 964 |
+
|
| 965 |
+
def _to_string(self, maxlen):
|
| 966 |
+
value = self._value
|
| 967 |
+
try:
|
| 968 |
+
return reverse_mapping[value]
|
| 969 |
+
except KeyError:
|
| 970 |
+
return str(value)
|
| 971 |
+
#
|
| 972 |
+
CTypesEnum._fix_class()
|
| 973 |
+
return CTypesEnum
|
| 974 |
+
|
| 975 |
+
def get_errno(self):
|
| 976 |
+
return ctypes.get_errno()
|
| 977 |
+
|
| 978 |
+
def set_errno(self, value):
|
| 979 |
+
ctypes.set_errno(value)
|
| 980 |
+
|
| 981 |
+
def string(self, b, maxlen=-1):
|
| 982 |
+
return b._to_string(maxlen)
|
| 983 |
+
|
| 984 |
+
def buffer(self, bptr, size=-1):
|
| 985 |
+
raise NotImplementedError("buffer() with ctypes backend")
|
| 986 |
+
|
| 987 |
+
def sizeof(self, cdata_or_BType):
|
| 988 |
+
if isinstance(cdata_or_BType, CTypesData):
|
| 989 |
+
return cdata_or_BType._get_size_of_instance()
|
| 990 |
+
else:
|
| 991 |
+
assert issubclass(cdata_or_BType, CTypesData)
|
| 992 |
+
return cdata_or_BType._get_size()
|
| 993 |
+
|
| 994 |
+
def alignof(self, BType):
|
| 995 |
+
assert issubclass(BType, CTypesData)
|
| 996 |
+
return BType._alignment()
|
| 997 |
+
|
| 998 |
+
def newp(self, BType, source):
|
| 999 |
+
if not issubclass(BType, CTypesData):
|
| 1000 |
+
raise TypeError
|
| 1001 |
+
return BType._newp(source)
|
| 1002 |
+
|
| 1003 |
+
def cast(self, BType, source):
|
| 1004 |
+
return BType._cast_from(source)
|
| 1005 |
+
|
| 1006 |
+
def callback(self, BType, source, error, onerror):
|
| 1007 |
+
assert onerror is None # XXX not implemented
|
| 1008 |
+
return BType(source, error)
|
| 1009 |
+
|
| 1010 |
+
_weakref_cache_ref = None
|
| 1011 |
+
|
| 1012 |
+
def gcp(self, cdata, destructor, size=0):
|
| 1013 |
+
if self._weakref_cache_ref is None:
|
| 1014 |
+
import weakref
|
| 1015 |
+
class MyRef(weakref.ref):
|
| 1016 |
+
def __eq__(self, other):
|
| 1017 |
+
myref = self()
|
| 1018 |
+
return self is other or (
|
| 1019 |
+
myref is not None and myref is other())
|
| 1020 |
+
def __ne__(self, other):
|
| 1021 |
+
return not (self == other)
|
| 1022 |
+
def __hash__(self):
|
| 1023 |
+
try:
|
| 1024 |
+
return self._hash
|
| 1025 |
+
except AttributeError:
|
| 1026 |
+
self._hash = hash(self())
|
| 1027 |
+
return self._hash
|
| 1028 |
+
self._weakref_cache_ref = {}, MyRef
|
| 1029 |
+
weak_cache, MyRef = self._weakref_cache_ref
|
| 1030 |
+
|
| 1031 |
+
if destructor is None:
|
| 1032 |
+
try:
|
| 1033 |
+
del weak_cache[MyRef(cdata)]
|
| 1034 |
+
except KeyError:
|
| 1035 |
+
raise TypeError("Can remove destructor only on a object "
|
| 1036 |
+
"previously returned by ffi.gc()")
|
| 1037 |
+
return None
|
| 1038 |
+
|
| 1039 |
+
def remove(k):
|
| 1040 |
+
cdata, destructor = weak_cache.pop(k, (None, None))
|
| 1041 |
+
if destructor is not None:
|
| 1042 |
+
destructor(cdata)
|
| 1043 |
+
|
| 1044 |
+
new_cdata = self.cast(self.typeof(cdata), cdata)
|
| 1045 |
+
assert new_cdata is not cdata
|
| 1046 |
+
weak_cache[MyRef(new_cdata, remove)] = (cdata, destructor)
|
| 1047 |
+
return new_cdata
|
| 1048 |
+
|
| 1049 |
+
typeof = type
|
| 1050 |
+
|
| 1051 |
+
def getcname(self, BType, replace_with):
|
| 1052 |
+
return BType._get_c_name(replace_with)
|
| 1053 |
+
|
| 1054 |
+
def typeoffsetof(self, BType, fieldname, num=0):
|
| 1055 |
+
if isinstance(fieldname, str):
|
| 1056 |
+
if num == 0 and issubclass(BType, CTypesGenericPtr):
|
| 1057 |
+
BType = BType._BItem
|
| 1058 |
+
if not issubclass(BType, CTypesBaseStructOrUnion):
|
| 1059 |
+
raise TypeError("expected a struct or union ctype")
|
| 1060 |
+
BField = BType._bfield_types[fieldname]
|
| 1061 |
+
if BField is Ellipsis:
|
| 1062 |
+
raise TypeError("not supported for bitfields")
|
| 1063 |
+
return (BField, BType._offsetof(fieldname))
|
| 1064 |
+
elif isinstance(fieldname, (int, long)):
|
| 1065 |
+
if issubclass(BType, CTypesGenericArray):
|
| 1066 |
+
BType = BType._CTPtr
|
| 1067 |
+
if not issubclass(BType, CTypesGenericPtr):
|
| 1068 |
+
raise TypeError("expected an array or ptr ctype")
|
| 1069 |
+
BItem = BType._BItem
|
| 1070 |
+
offset = BItem._get_size() * fieldname
|
| 1071 |
+
if offset > sys.maxsize:
|
| 1072 |
+
raise OverflowError
|
| 1073 |
+
return (BItem, offset)
|
| 1074 |
+
else:
|
| 1075 |
+
raise TypeError(type(fieldname))
|
| 1076 |
+
|
| 1077 |
+
def rawaddressof(self, BTypePtr, cdata, offset=None):
|
| 1078 |
+
if isinstance(cdata, CTypesBaseStructOrUnion):
|
| 1079 |
+
ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata))
|
| 1080 |
+
elif isinstance(cdata, CTypesGenericPtr):
|
| 1081 |
+
if offset is None or not issubclass(type(cdata)._BItem,
|
| 1082 |
+
CTypesBaseStructOrUnion):
|
| 1083 |
+
raise TypeError("unexpected cdata type")
|
| 1084 |
+
ptr = type(cdata)._to_ctypes(cdata)
|
| 1085 |
+
elif isinstance(cdata, CTypesGenericArray):
|
| 1086 |
+
ptr = type(cdata)._to_ctypes(cdata)
|
| 1087 |
+
else:
|
| 1088 |
+
raise TypeError("expected a <cdata 'struct-or-union'>")
|
| 1089 |
+
if offset:
|
| 1090 |
+
ptr = ctypes.cast(
|
| 1091 |
+
ctypes.c_void_p(
|
| 1092 |
+
ctypes.cast(ptr, ctypes.c_void_p).value + offset),
|
| 1093 |
+
type(ptr))
|
| 1094 |
+
return BTypePtr._from_ctypes(ptr)
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
class CTypesLibrary(object):
|
| 1098 |
+
|
| 1099 |
+
def __init__(self, backend, cdll):
|
| 1100 |
+
self.backend = backend
|
| 1101 |
+
self.cdll = cdll
|
| 1102 |
+
|
| 1103 |
+
def load_function(self, BType, name):
|
| 1104 |
+
c_func = getattr(self.cdll, name)
|
| 1105 |
+
funcobj = BType._from_ctypes(c_func)
|
| 1106 |
+
funcobj._name = name
|
| 1107 |
+
return funcobj
|
| 1108 |
+
|
| 1109 |
+
def read_variable(self, BType, name):
|
| 1110 |
+
try:
|
| 1111 |
+
ctypes_obj = BType._ctype.in_dll(self.cdll, name)
|
| 1112 |
+
except AttributeError as e:
|
| 1113 |
+
raise NotImplementedError(e)
|
| 1114 |
+
return BType._from_ctypes(ctypes_obj)
|
| 1115 |
+
|
| 1116 |
+
def write_variable(self, BType, name, value):
|
| 1117 |
+
new_ctypes_obj = BType._to_ctypes(value)
|
| 1118 |
+
ctypes_obj = BType._ctype.in_dll(self.cdll, name)
|
| 1119 |
+
ctypes.memmove(ctypes.addressof(ctypes_obj),
|
| 1120 |
+
ctypes.addressof(new_ctypes_obj),
|
| 1121 |
+
ctypes.sizeof(BType._ctype))
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cffi_opcode.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .error import VerificationError
|
| 2 |
+
|
| 3 |
+
class CffiOp(object):
|
| 4 |
+
def __init__(self, op, arg):
|
| 5 |
+
self.op = op
|
| 6 |
+
self.arg = arg
|
| 7 |
+
|
| 8 |
+
def as_c_expr(self):
|
| 9 |
+
if self.op is None:
|
| 10 |
+
assert isinstance(self.arg, str)
|
| 11 |
+
return '(_cffi_opcode_t)(%s)' % (self.arg,)
|
| 12 |
+
classname = CLASS_NAME[self.op]
|
| 13 |
+
return '_CFFI_OP(_CFFI_OP_%s, %s)' % (classname, self.arg)
|
| 14 |
+
|
| 15 |
+
def as_python_bytes(self):
|
| 16 |
+
if self.op is None and self.arg.isdigit():
|
| 17 |
+
value = int(self.arg) # non-negative: '-' not in self.arg
|
| 18 |
+
if value >= 2**31:
|
| 19 |
+
raise OverflowError("cannot emit %r: limited to 2**31-1"
|
| 20 |
+
% (self.arg,))
|
| 21 |
+
return format_four_bytes(value)
|
| 22 |
+
if isinstance(self.arg, str):
|
| 23 |
+
raise VerificationError("cannot emit to Python: %r" % (self.arg,))
|
| 24 |
+
return format_four_bytes((self.arg << 8) | self.op)
|
| 25 |
+
|
| 26 |
+
def __str__(self):
|
| 27 |
+
classname = CLASS_NAME.get(self.op, self.op)
|
| 28 |
+
return '(%s %s)' % (classname, self.arg)
|
| 29 |
+
|
| 30 |
+
def format_four_bytes(num):
|
| 31 |
+
return '\\x%02X\\x%02X\\x%02X\\x%02X' % (
|
| 32 |
+
(num >> 24) & 0xFF,
|
| 33 |
+
(num >> 16) & 0xFF,
|
| 34 |
+
(num >> 8) & 0xFF,
|
| 35 |
+
(num ) & 0xFF)
|
| 36 |
+
|
| 37 |
+
OP_PRIMITIVE = 1
|
| 38 |
+
OP_POINTER = 3
|
| 39 |
+
OP_ARRAY = 5
|
| 40 |
+
OP_OPEN_ARRAY = 7
|
| 41 |
+
OP_STRUCT_UNION = 9
|
| 42 |
+
OP_ENUM = 11
|
| 43 |
+
OP_FUNCTION = 13
|
| 44 |
+
OP_FUNCTION_END = 15
|
| 45 |
+
OP_NOOP = 17
|
| 46 |
+
OP_BITFIELD = 19
|
| 47 |
+
OP_TYPENAME = 21
|
| 48 |
+
OP_CPYTHON_BLTN_V = 23 # varargs
|
| 49 |
+
OP_CPYTHON_BLTN_N = 25 # noargs
|
| 50 |
+
OP_CPYTHON_BLTN_O = 27 # O (i.e. a single arg)
|
| 51 |
+
OP_CONSTANT = 29
|
| 52 |
+
OP_CONSTANT_INT = 31
|
| 53 |
+
OP_GLOBAL_VAR = 33
|
| 54 |
+
OP_DLOPEN_FUNC = 35
|
| 55 |
+
OP_DLOPEN_CONST = 37
|
| 56 |
+
OP_GLOBAL_VAR_F = 39
|
| 57 |
+
OP_EXTERN_PYTHON = 41
|
| 58 |
+
|
| 59 |
+
PRIM_VOID = 0
|
| 60 |
+
PRIM_BOOL = 1
|
| 61 |
+
PRIM_CHAR = 2
|
| 62 |
+
PRIM_SCHAR = 3
|
| 63 |
+
PRIM_UCHAR = 4
|
| 64 |
+
PRIM_SHORT = 5
|
| 65 |
+
PRIM_USHORT = 6
|
| 66 |
+
PRIM_INT = 7
|
| 67 |
+
PRIM_UINT = 8
|
| 68 |
+
PRIM_LONG = 9
|
| 69 |
+
PRIM_ULONG = 10
|
| 70 |
+
PRIM_LONGLONG = 11
|
| 71 |
+
PRIM_ULONGLONG = 12
|
| 72 |
+
PRIM_FLOAT = 13
|
| 73 |
+
PRIM_DOUBLE = 14
|
| 74 |
+
PRIM_LONGDOUBLE = 15
|
| 75 |
+
|
| 76 |
+
PRIM_WCHAR = 16
|
| 77 |
+
PRIM_INT8 = 17
|
| 78 |
+
PRIM_UINT8 = 18
|
| 79 |
+
PRIM_INT16 = 19
|
| 80 |
+
PRIM_UINT16 = 20
|
| 81 |
+
PRIM_INT32 = 21
|
| 82 |
+
PRIM_UINT32 = 22
|
| 83 |
+
PRIM_INT64 = 23
|
| 84 |
+
PRIM_UINT64 = 24
|
| 85 |
+
PRIM_INTPTR = 25
|
| 86 |
+
PRIM_UINTPTR = 26
|
| 87 |
+
PRIM_PTRDIFF = 27
|
| 88 |
+
PRIM_SIZE = 28
|
| 89 |
+
PRIM_SSIZE = 29
|
| 90 |
+
PRIM_INT_LEAST8 = 30
|
| 91 |
+
PRIM_UINT_LEAST8 = 31
|
| 92 |
+
PRIM_INT_LEAST16 = 32
|
| 93 |
+
PRIM_UINT_LEAST16 = 33
|
| 94 |
+
PRIM_INT_LEAST32 = 34
|
| 95 |
+
PRIM_UINT_LEAST32 = 35
|
| 96 |
+
PRIM_INT_LEAST64 = 36
|
| 97 |
+
PRIM_UINT_LEAST64 = 37
|
| 98 |
+
PRIM_INT_FAST8 = 38
|
| 99 |
+
PRIM_UINT_FAST8 = 39
|
| 100 |
+
PRIM_INT_FAST16 = 40
|
| 101 |
+
PRIM_UINT_FAST16 = 41
|
| 102 |
+
PRIM_INT_FAST32 = 42
|
| 103 |
+
PRIM_UINT_FAST32 = 43
|
| 104 |
+
PRIM_INT_FAST64 = 44
|
| 105 |
+
PRIM_UINT_FAST64 = 45
|
| 106 |
+
PRIM_INTMAX = 46
|
| 107 |
+
PRIM_UINTMAX = 47
|
| 108 |
+
PRIM_FLOATCOMPLEX = 48
|
| 109 |
+
PRIM_DOUBLECOMPLEX = 49
|
| 110 |
+
PRIM_CHAR16 = 50
|
| 111 |
+
PRIM_CHAR32 = 51
|
| 112 |
+
|
| 113 |
+
_NUM_PRIM = 52
|
| 114 |
+
_UNKNOWN_PRIM = -1
|
| 115 |
+
_UNKNOWN_FLOAT_PRIM = -2
|
| 116 |
+
_UNKNOWN_LONG_DOUBLE = -3
|
| 117 |
+
|
| 118 |
+
_IO_FILE_STRUCT = -1
|
| 119 |
+
|
| 120 |
+
PRIMITIVE_TO_INDEX = {
|
| 121 |
+
'char': PRIM_CHAR,
|
| 122 |
+
'short': PRIM_SHORT,
|
| 123 |
+
'int': PRIM_INT,
|
| 124 |
+
'long': PRIM_LONG,
|
| 125 |
+
'long long': PRIM_LONGLONG,
|
| 126 |
+
'signed char': PRIM_SCHAR,
|
| 127 |
+
'unsigned char': PRIM_UCHAR,
|
| 128 |
+
'unsigned short': PRIM_USHORT,
|
| 129 |
+
'unsigned int': PRIM_UINT,
|
| 130 |
+
'unsigned long': PRIM_ULONG,
|
| 131 |
+
'unsigned long long': PRIM_ULONGLONG,
|
| 132 |
+
'float': PRIM_FLOAT,
|
| 133 |
+
'double': PRIM_DOUBLE,
|
| 134 |
+
'long double': PRIM_LONGDOUBLE,
|
| 135 |
+
'_cffi_float_complex_t': PRIM_FLOATCOMPLEX,
|
| 136 |
+
'_cffi_double_complex_t': PRIM_DOUBLECOMPLEX,
|
| 137 |
+
'_Bool': PRIM_BOOL,
|
| 138 |
+
'wchar_t': PRIM_WCHAR,
|
| 139 |
+
'char16_t': PRIM_CHAR16,
|
| 140 |
+
'char32_t': PRIM_CHAR32,
|
| 141 |
+
'int8_t': PRIM_INT8,
|
| 142 |
+
'uint8_t': PRIM_UINT8,
|
| 143 |
+
'int16_t': PRIM_INT16,
|
| 144 |
+
'uint16_t': PRIM_UINT16,
|
| 145 |
+
'int32_t': PRIM_INT32,
|
| 146 |
+
'uint32_t': PRIM_UINT32,
|
| 147 |
+
'int64_t': PRIM_INT64,
|
| 148 |
+
'uint64_t': PRIM_UINT64,
|
| 149 |
+
'intptr_t': PRIM_INTPTR,
|
| 150 |
+
'uintptr_t': PRIM_UINTPTR,
|
| 151 |
+
'ptrdiff_t': PRIM_PTRDIFF,
|
| 152 |
+
'size_t': PRIM_SIZE,
|
| 153 |
+
'ssize_t': PRIM_SSIZE,
|
| 154 |
+
'int_least8_t': PRIM_INT_LEAST8,
|
| 155 |
+
'uint_least8_t': PRIM_UINT_LEAST8,
|
| 156 |
+
'int_least16_t': PRIM_INT_LEAST16,
|
| 157 |
+
'uint_least16_t': PRIM_UINT_LEAST16,
|
| 158 |
+
'int_least32_t': PRIM_INT_LEAST32,
|
| 159 |
+
'uint_least32_t': PRIM_UINT_LEAST32,
|
| 160 |
+
'int_least64_t': PRIM_INT_LEAST64,
|
| 161 |
+
'uint_least64_t': PRIM_UINT_LEAST64,
|
| 162 |
+
'int_fast8_t': PRIM_INT_FAST8,
|
| 163 |
+
'uint_fast8_t': PRIM_UINT_FAST8,
|
| 164 |
+
'int_fast16_t': PRIM_INT_FAST16,
|
| 165 |
+
'uint_fast16_t': PRIM_UINT_FAST16,
|
| 166 |
+
'int_fast32_t': PRIM_INT_FAST32,
|
| 167 |
+
'uint_fast32_t': PRIM_UINT_FAST32,
|
| 168 |
+
'int_fast64_t': PRIM_INT_FAST64,
|
| 169 |
+
'uint_fast64_t': PRIM_UINT_FAST64,
|
| 170 |
+
'intmax_t': PRIM_INTMAX,
|
| 171 |
+
'uintmax_t': PRIM_UINTMAX,
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
F_UNION = 0x01
|
| 175 |
+
F_CHECK_FIELDS = 0x02
|
| 176 |
+
F_PACKED = 0x04
|
| 177 |
+
F_EXTERNAL = 0x08
|
| 178 |
+
F_OPAQUE = 0x10
|
| 179 |
+
|
| 180 |
+
G_FLAGS = dict([('_CFFI_' + _key, globals()[_key])
|
| 181 |
+
for _key in ['F_UNION', 'F_CHECK_FIELDS', 'F_PACKED',
|
| 182 |
+
'F_EXTERNAL', 'F_OPAQUE']])
|
| 183 |
+
|
| 184 |
+
CLASS_NAME = {}
|
| 185 |
+
for _name, _value in list(globals().items()):
|
| 186 |
+
if _name.startswith('OP_') and isinstance(_value, int):
|
| 187 |
+
CLASS_NAME[_value] = _name[3:]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/commontypes.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from . import model
|
| 3 |
+
from .error import FFIError
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
COMMON_TYPES = {}
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
# fetch "bool" and all simple Windows types
|
| 10 |
+
from _cffi_backend import _get_common_types
|
| 11 |
+
_get_common_types(COMMON_TYPES)
|
| 12 |
+
except ImportError:
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE')
|
| 16 |
+
COMMON_TYPES['bool'] = '_Bool' # in case we got ImportError above
|
| 17 |
+
COMMON_TYPES['float _Complex'] = '_cffi_float_complex_t'
|
| 18 |
+
COMMON_TYPES['double _Complex'] = '_cffi_double_complex_t'
|
| 19 |
+
|
| 20 |
+
for _type in model.PrimitiveType.ALL_PRIMITIVE_TYPES:
|
| 21 |
+
if _type.endswith('_t'):
|
| 22 |
+
COMMON_TYPES[_type] = _type
|
| 23 |
+
del _type
|
| 24 |
+
|
| 25 |
+
_CACHE = {}
|
| 26 |
+
|
| 27 |
+
def resolve_common_type(parser, commontype):
|
| 28 |
+
try:
|
| 29 |
+
return _CACHE[commontype]
|
| 30 |
+
except KeyError:
|
| 31 |
+
cdecl = COMMON_TYPES.get(commontype, commontype)
|
| 32 |
+
if not isinstance(cdecl, str):
|
| 33 |
+
result, quals = cdecl, 0 # cdecl is already a BaseType
|
| 34 |
+
elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES:
|
| 35 |
+
result, quals = model.PrimitiveType(cdecl), 0
|
| 36 |
+
elif cdecl == 'set-unicode-needed':
|
| 37 |
+
raise FFIError("The Windows type %r is only available after "
|
| 38 |
+
"you call ffi.set_unicode()" % (commontype,))
|
| 39 |
+
else:
|
| 40 |
+
if commontype == cdecl:
|
| 41 |
+
raise FFIError(
|
| 42 |
+
"Unsupported type: %r. Please look at "
|
| 43 |
+
"http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations "
|
| 44 |
+
"and file an issue if you think this type should really "
|
| 45 |
+
"be supported." % (commontype,))
|
| 46 |
+
result, quals = parser.parse_type_and_quals(cdecl) # recursive
|
| 47 |
+
|
| 48 |
+
assert isinstance(result, model.BaseTypeByIdentity)
|
| 49 |
+
_CACHE[commontype] = result, quals
|
| 50 |
+
return result, quals
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# ____________________________________________________________
|
| 54 |
+
# extra types for Windows (most of them are in commontypes.c)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def win_common_types():
|
| 58 |
+
return {
|
| 59 |
+
"UNICODE_STRING": model.StructType(
|
| 60 |
+
"_UNICODE_STRING",
|
| 61 |
+
["Length",
|
| 62 |
+
"MaximumLength",
|
| 63 |
+
"Buffer"],
|
| 64 |
+
[model.PrimitiveType("unsigned short"),
|
| 65 |
+
model.PrimitiveType("unsigned short"),
|
| 66 |
+
model.PointerType(model.PrimitiveType("wchar_t"))],
|
| 67 |
+
[-1, -1, -1]),
|
| 68 |
+
"PUNICODE_STRING": "UNICODE_STRING *",
|
| 69 |
+
"PCUNICODE_STRING": "const UNICODE_STRING *",
|
| 70 |
+
|
| 71 |
+
"TBYTE": "set-unicode-needed",
|
| 72 |
+
"TCHAR": "set-unicode-needed",
|
| 73 |
+
"LPCTSTR": "set-unicode-needed",
|
| 74 |
+
"PCTSTR": "set-unicode-needed",
|
| 75 |
+
"LPTSTR": "set-unicode-needed",
|
| 76 |
+
"PTSTR": "set-unicode-needed",
|
| 77 |
+
"PTBYTE": "set-unicode-needed",
|
| 78 |
+
"PTCHAR": "set-unicode-needed",
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
if sys.platform == 'win32':
|
| 82 |
+
COMMON_TYPES.update(win_common_types())
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/cparser.py
ADDED
|
@@ -0,0 +1,1015 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import model
|
| 2 |
+
from .commontypes import COMMON_TYPES, resolve_common_type
|
| 3 |
+
from .error import FFIError, CDefError
|
| 4 |
+
try:
|
| 5 |
+
from . import _pycparser as pycparser
|
| 6 |
+
except ImportError:
|
| 7 |
+
import pycparser
|
| 8 |
+
import weakref, re, sys
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
if sys.version_info < (3,):
|
| 12 |
+
import thread as _thread
|
| 13 |
+
else:
|
| 14 |
+
import _thread
|
| 15 |
+
lock = _thread.allocate_lock()
|
| 16 |
+
except ImportError:
|
| 17 |
+
lock = None
|
| 18 |
+
|
| 19 |
+
def _workaround_for_static_import_finders():
|
| 20 |
+
# Issue #392: packaging tools like cx_Freeze can not find these
|
| 21 |
+
# because pycparser uses exec dynamic import. This is an obscure
|
| 22 |
+
# workaround. This function is never called.
|
| 23 |
+
import pycparser.yacctab
|
| 24 |
+
import pycparser.lextab
|
| 25 |
+
|
| 26 |
+
CDEF_SOURCE_STRING = "<cdef source string>"
|
| 27 |
+
_r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$",
|
| 28 |
+
re.DOTALL | re.MULTILINE)
|
| 29 |
+
_r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)"
|
| 30 |
+
r"\b((?:[^\n\\]|\\.)*?)$",
|
| 31 |
+
re.DOTALL | re.MULTILINE)
|
| 32 |
+
_r_line_directive = re.compile(r"^[ \t]*#[ \t]*(?:line|\d+)\b.*$", re.MULTILINE)
|
| 33 |
+
_r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}")
|
| 34 |
+
_r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$")
|
| 35 |
+
_r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]")
|
| 36 |
+
_r_words = re.compile(r"\w+|\S")
|
| 37 |
+
_parser_cache = None
|
| 38 |
+
_r_int_literal = re.compile(r"-?0?x?[0-9a-f]+[lu]*$", re.IGNORECASE)
|
| 39 |
+
_r_stdcall1 = re.compile(r"\b(__stdcall|WINAPI)\b")
|
| 40 |
+
_r_stdcall2 = re.compile(r"[(]\s*(__stdcall|WINAPI)\b")
|
| 41 |
+
_r_cdecl = re.compile(r"\b__cdecl\b")
|
| 42 |
+
_r_extern_python = re.compile(r'\bextern\s*"'
|
| 43 |
+
r'(Python|Python\s*\+\s*C|C\s*\+\s*Python)"\s*.')
|
| 44 |
+
_r_star_const_space = re.compile( # matches "* const "
|
| 45 |
+
r"[*]\s*((const|volatile|restrict)\b\s*)+")
|
| 46 |
+
_r_int_dotdotdot = re.compile(r"(\b(int|long|short|signed|unsigned|char)\s*)+"
|
| 47 |
+
r"\.\.\.")
|
| 48 |
+
_r_float_dotdotdot = re.compile(r"\b(double|float)\s*\.\.\.")
|
| 49 |
+
|
| 50 |
+
def _get_parser():
|
| 51 |
+
global _parser_cache
|
| 52 |
+
if _parser_cache is None:
|
| 53 |
+
_parser_cache = pycparser.CParser()
|
| 54 |
+
return _parser_cache
|
| 55 |
+
|
| 56 |
+
def _workaround_for_old_pycparser(csource):
|
| 57 |
+
# Workaround for a pycparser issue (fixed between pycparser 2.10 and
|
| 58 |
+
# 2.14): "char*const***" gives us a wrong syntax tree, the same as
|
| 59 |
+
# for "char***(*const)". This means we can't tell the difference
|
| 60 |
+
# afterwards. But "char(*const(***))" gives us the right syntax
|
| 61 |
+
# tree. The issue only occurs if there are several stars in
|
| 62 |
+
# sequence with no parenthesis in between, just possibly qualifiers.
|
| 63 |
+
# Attempt to fix it by adding some parentheses in the source: each
|
| 64 |
+
# time we see "* const" or "* const *", we add an opening
|
| 65 |
+
# parenthesis before each star---the hard part is figuring out where
|
| 66 |
+
# to close them.
|
| 67 |
+
parts = []
|
| 68 |
+
while True:
|
| 69 |
+
match = _r_star_const_space.search(csource)
|
| 70 |
+
if not match:
|
| 71 |
+
break
|
| 72 |
+
#print repr(''.join(parts)+csource), '=>',
|
| 73 |
+
parts.append(csource[:match.start()])
|
| 74 |
+
parts.append('('); closing = ')'
|
| 75 |
+
parts.append(match.group()) # e.g. "* const "
|
| 76 |
+
endpos = match.end()
|
| 77 |
+
if csource.startswith('*', endpos):
|
| 78 |
+
parts.append('('); closing += ')'
|
| 79 |
+
level = 0
|
| 80 |
+
i = endpos
|
| 81 |
+
while i < len(csource):
|
| 82 |
+
c = csource[i]
|
| 83 |
+
if c == '(':
|
| 84 |
+
level += 1
|
| 85 |
+
elif c == ')':
|
| 86 |
+
if level == 0:
|
| 87 |
+
break
|
| 88 |
+
level -= 1
|
| 89 |
+
elif c in ',;=':
|
| 90 |
+
if level == 0:
|
| 91 |
+
break
|
| 92 |
+
i += 1
|
| 93 |
+
csource = csource[endpos:i] + closing + csource[i:]
|
| 94 |
+
#print repr(''.join(parts)+csource)
|
| 95 |
+
parts.append(csource)
|
| 96 |
+
return ''.join(parts)
|
| 97 |
+
|
| 98 |
+
def _preprocess_extern_python(csource):
|
| 99 |
+
# input: `extern "Python" int foo(int);` or
|
| 100 |
+
# `extern "Python" { int foo(int); }`
|
| 101 |
+
# output:
|
| 102 |
+
# void __cffi_extern_python_start;
|
| 103 |
+
# int foo(int);
|
| 104 |
+
# void __cffi_extern_python_stop;
|
| 105 |
+
#
|
| 106 |
+
# input: `extern "Python+C" int foo(int);`
|
| 107 |
+
# output:
|
| 108 |
+
# void __cffi_extern_python_plus_c_start;
|
| 109 |
+
# int foo(int);
|
| 110 |
+
# void __cffi_extern_python_stop;
|
| 111 |
+
parts = []
|
| 112 |
+
while True:
|
| 113 |
+
match = _r_extern_python.search(csource)
|
| 114 |
+
if not match:
|
| 115 |
+
break
|
| 116 |
+
endpos = match.end() - 1
|
| 117 |
+
#print
|
| 118 |
+
#print ''.join(parts)+csource
|
| 119 |
+
#print '=>'
|
| 120 |
+
parts.append(csource[:match.start()])
|
| 121 |
+
if 'C' in match.group(1):
|
| 122 |
+
parts.append('void __cffi_extern_python_plus_c_start; ')
|
| 123 |
+
else:
|
| 124 |
+
parts.append('void __cffi_extern_python_start; ')
|
| 125 |
+
if csource[endpos] == '{':
|
| 126 |
+
# grouping variant
|
| 127 |
+
closing = csource.find('}', endpos)
|
| 128 |
+
if closing < 0:
|
| 129 |
+
raise CDefError("'extern \"Python\" {': no '}' found")
|
| 130 |
+
if csource.find('{', endpos + 1, closing) >= 0:
|
| 131 |
+
raise NotImplementedError("cannot use { } inside a block "
|
| 132 |
+
"'extern \"Python\" { ... }'")
|
| 133 |
+
parts.append(csource[endpos+1:closing])
|
| 134 |
+
csource = csource[closing+1:]
|
| 135 |
+
else:
|
| 136 |
+
# non-grouping variant
|
| 137 |
+
semicolon = csource.find(';', endpos)
|
| 138 |
+
if semicolon < 0:
|
| 139 |
+
raise CDefError("'extern \"Python\": no ';' found")
|
| 140 |
+
parts.append(csource[endpos:semicolon+1])
|
| 141 |
+
csource = csource[semicolon+1:]
|
| 142 |
+
parts.append(' void __cffi_extern_python_stop;')
|
| 143 |
+
#print ''.join(parts)+csource
|
| 144 |
+
#print
|
| 145 |
+
parts.append(csource)
|
| 146 |
+
return ''.join(parts)
|
| 147 |
+
|
| 148 |
+
def _warn_for_string_literal(csource):
|
| 149 |
+
if '"' not in csource:
|
| 150 |
+
return
|
| 151 |
+
for line in csource.splitlines():
|
| 152 |
+
if '"' in line and not line.lstrip().startswith('#'):
|
| 153 |
+
import warnings
|
| 154 |
+
warnings.warn("String literal found in cdef() or type source. "
|
| 155 |
+
"String literals are ignored here, but you should "
|
| 156 |
+
"remove them anyway because some character sequences "
|
| 157 |
+
"confuse pre-parsing.")
|
| 158 |
+
break
|
| 159 |
+
|
| 160 |
+
def _warn_for_non_extern_non_static_global_variable(decl):
|
| 161 |
+
if not decl.storage:
|
| 162 |
+
import warnings
|
| 163 |
+
warnings.warn("Global variable '%s' in cdef(): for consistency "
|
| 164 |
+
"with C it should have a storage class specifier "
|
| 165 |
+
"(usually 'extern')" % (decl.name,))
|
| 166 |
+
|
| 167 |
+
def _remove_line_directives(csource):
|
| 168 |
+
# _r_line_directive matches whole lines, without the final \n, if they
|
| 169 |
+
# start with '#line' with some spacing allowed, or '#NUMBER'. This
|
| 170 |
+
# function stores them away and replaces them with exactly the string
|
| 171 |
+
# '#line@N', where N is the index in the list 'line_directives'.
|
| 172 |
+
line_directives = []
|
| 173 |
+
def replace(m):
|
| 174 |
+
i = len(line_directives)
|
| 175 |
+
line_directives.append(m.group())
|
| 176 |
+
return '#line@%d' % i
|
| 177 |
+
csource = _r_line_directive.sub(replace, csource)
|
| 178 |
+
return csource, line_directives
|
| 179 |
+
|
| 180 |
+
def _put_back_line_directives(csource, line_directives):
|
| 181 |
+
def replace(m):
|
| 182 |
+
s = m.group()
|
| 183 |
+
if not s.startswith('#line@'):
|
| 184 |
+
raise AssertionError("unexpected #line directive "
|
| 185 |
+
"(should have been processed and removed")
|
| 186 |
+
return line_directives[int(s[6:])]
|
| 187 |
+
return _r_line_directive.sub(replace, csource)
|
| 188 |
+
|
| 189 |
+
def _preprocess(csource):
|
| 190 |
+
# First, remove the lines of the form '#line N "filename"' because
|
| 191 |
+
# the "filename" part could confuse the rest
|
| 192 |
+
csource, line_directives = _remove_line_directives(csource)
|
| 193 |
+
# Remove comments. NOTE: this only work because the cdef() section
|
| 194 |
+
# should not contain any string literals (except in line directives)!
|
| 195 |
+
def replace_keeping_newlines(m):
|
| 196 |
+
return ' ' + m.group().count('\n') * '\n'
|
| 197 |
+
csource = _r_comment.sub(replace_keeping_newlines, csource)
|
| 198 |
+
# Remove the "#define FOO x" lines
|
| 199 |
+
macros = {}
|
| 200 |
+
for match in _r_define.finditer(csource):
|
| 201 |
+
macroname, macrovalue = match.groups()
|
| 202 |
+
macrovalue = macrovalue.replace('\\\n', '').strip()
|
| 203 |
+
macros[macroname] = macrovalue
|
| 204 |
+
csource = _r_define.sub('', csource)
|
| 205 |
+
#
|
| 206 |
+
if pycparser.__version__ < '2.14':
|
| 207 |
+
csource = _workaround_for_old_pycparser(csource)
|
| 208 |
+
#
|
| 209 |
+
# BIG HACK: replace WINAPI or __stdcall with "volatile const".
|
| 210 |
+
# It doesn't make sense for the return type of a function to be
|
| 211 |
+
# "volatile volatile const", so we abuse it to detect __stdcall...
|
| 212 |
+
# Hack number 2 is that "int(volatile *fptr)();" is not valid C
|
| 213 |
+
# syntax, so we place the "volatile" before the opening parenthesis.
|
| 214 |
+
csource = _r_stdcall2.sub(' volatile volatile const(', csource)
|
| 215 |
+
csource = _r_stdcall1.sub(' volatile volatile const ', csource)
|
| 216 |
+
csource = _r_cdecl.sub(' ', csource)
|
| 217 |
+
#
|
| 218 |
+
# Replace `extern "Python"` with start/end markers
|
| 219 |
+
csource = _preprocess_extern_python(csource)
|
| 220 |
+
#
|
| 221 |
+
# Now there should not be any string literal left; warn if we get one
|
| 222 |
+
_warn_for_string_literal(csource)
|
| 223 |
+
#
|
| 224 |
+
# Replace "[...]" with "[__dotdotdotarray__]"
|
| 225 |
+
csource = _r_partial_array.sub('[__dotdotdotarray__]', csource)
|
| 226 |
+
#
|
| 227 |
+
# Replace "...}" with "__dotdotdotNUM__}". This construction should
|
| 228 |
+
# occur only at the end of enums; at the end of structs we have "...;}"
|
| 229 |
+
# and at the end of vararg functions "...);". Also replace "=...[,}]"
|
| 230 |
+
# with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when
|
| 231 |
+
# giving an unknown value.
|
| 232 |
+
matches = list(_r_partial_enum.finditer(csource))
|
| 233 |
+
for number, match in enumerate(reversed(matches)):
|
| 234 |
+
p = match.start()
|
| 235 |
+
if csource[p] == '=':
|
| 236 |
+
p2 = csource.find('...', p, match.end())
|
| 237 |
+
assert p2 > p
|
| 238 |
+
csource = '%s,__dotdotdot%d__ %s' % (csource[:p], number,
|
| 239 |
+
csource[p2+3:])
|
| 240 |
+
else:
|
| 241 |
+
assert csource[p:p+3] == '...'
|
| 242 |
+
csource = '%s __dotdotdot%d__ %s' % (csource[:p], number,
|
| 243 |
+
csource[p+3:])
|
| 244 |
+
# Replace "int ..." or "unsigned long int..." with "__dotdotdotint__"
|
| 245 |
+
csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource)
|
| 246 |
+
# Replace "float ..." or "double..." with "__dotdotdotfloat__"
|
| 247 |
+
csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource)
|
| 248 |
+
# Replace all remaining "..." with the same name, "__dotdotdot__",
|
| 249 |
+
# which is declared with a typedef for the purpose of C parsing.
|
| 250 |
+
csource = csource.replace('...', ' __dotdotdot__ ')
|
| 251 |
+
# Finally, put back the line directives
|
| 252 |
+
csource = _put_back_line_directives(csource, line_directives)
|
| 253 |
+
return csource, macros
|
| 254 |
+
|
| 255 |
+
def _common_type_names(csource):
|
| 256 |
+
# Look in the source for what looks like usages of types from the
|
| 257 |
+
# list of common types. A "usage" is approximated here as the
|
| 258 |
+
# appearance of the word, minus a "definition" of the type, which
|
| 259 |
+
# is the last word in a "typedef" statement. Approximative only
|
| 260 |
+
# but should be fine for all the common types.
|
| 261 |
+
look_for_words = set(COMMON_TYPES)
|
| 262 |
+
look_for_words.add(';')
|
| 263 |
+
look_for_words.add(',')
|
| 264 |
+
look_for_words.add('(')
|
| 265 |
+
look_for_words.add(')')
|
| 266 |
+
look_for_words.add('typedef')
|
| 267 |
+
words_used = set()
|
| 268 |
+
is_typedef = False
|
| 269 |
+
paren = 0
|
| 270 |
+
previous_word = ''
|
| 271 |
+
for word in _r_words.findall(csource):
|
| 272 |
+
if word in look_for_words:
|
| 273 |
+
if word == ';':
|
| 274 |
+
if is_typedef:
|
| 275 |
+
words_used.discard(previous_word)
|
| 276 |
+
look_for_words.discard(previous_word)
|
| 277 |
+
is_typedef = False
|
| 278 |
+
elif word == 'typedef':
|
| 279 |
+
is_typedef = True
|
| 280 |
+
paren = 0
|
| 281 |
+
elif word == '(':
|
| 282 |
+
paren += 1
|
| 283 |
+
elif word == ')':
|
| 284 |
+
paren -= 1
|
| 285 |
+
elif word == ',':
|
| 286 |
+
if is_typedef and paren == 0:
|
| 287 |
+
words_used.discard(previous_word)
|
| 288 |
+
look_for_words.discard(previous_word)
|
| 289 |
+
else: # word in COMMON_TYPES
|
| 290 |
+
words_used.add(word)
|
| 291 |
+
previous_word = word
|
| 292 |
+
return words_used
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class Parser(object):
|
| 296 |
+
|
| 297 |
+
def __init__(self):
|
| 298 |
+
self._declarations = {}
|
| 299 |
+
self._included_declarations = set()
|
| 300 |
+
self._anonymous_counter = 0
|
| 301 |
+
self._structnode2type = weakref.WeakKeyDictionary()
|
| 302 |
+
self._options = {}
|
| 303 |
+
self._int_constants = {}
|
| 304 |
+
self._recomplete = []
|
| 305 |
+
self._uses_new_feature = None
|
| 306 |
+
|
| 307 |
+
def _parse(self, csource):
|
| 308 |
+
csource, macros = _preprocess(csource)
|
| 309 |
+
# XXX: for more efficiency we would need to poke into the
|
| 310 |
+
# internals of CParser... the following registers the
|
| 311 |
+
# typedefs, because their presence or absence influences the
|
| 312 |
+
# parsing itself (but what they are typedef'ed to plays no role)
|
| 313 |
+
ctn = _common_type_names(csource)
|
| 314 |
+
typenames = []
|
| 315 |
+
for name in sorted(self._declarations):
|
| 316 |
+
if name.startswith('typedef '):
|
| 317 |
+
name = name[8:]
|
| 318 |
+
typenames.append(name)
|
| 319 |
+
ctn.discard(name)
|
| 320 |
+
typenames += sorted(ctn)
|
| 321 |
+
#
|
| 322 |
+
csourcelines = []
|
| 323 |
+
csourcelines.append('# 1 "<cdef automatic initialization code>"')
|
| 324 |
+
for typename in typenames:
|
| 325 |
+
csourcelines.append('typedef int %s;' % typename)
|
| 326 |
+
csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,'
|
| 327 |
+
' __dotdotdot__;')
|
| 328 |
+
# this forces pycparser to consider the following in the file
|
| 329 |
+
# called <cdef source string> from line 1
|
| 330 |
+
csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,))
|
| 331 |
+
csourcelines.append(csource)
|
| 332 |
+
csourcelines.append('') # see test_missing_newline_bug
|
| 333 |
+
fullcsource = '\n'.join(csourcelines)
|
| 334 |
+
if lock is not None:
|
| 335 |
+
lock.acquire() # pycparser is not thread-safe...
|
| 336 |
+
try:
|
| 337 |
+
ast = _get_parser().parse(fullcsource)
|
| 338 |
+
except pycparser.c_parser.ParseError as e:
|
| 339 |
+
self.convert_pycparser_error(e, csource)
|
| 340 |
+
finally:
|
| 341 |
+
if lock is not None:
|
| 342 |
+
lock.release()
|
| 343 |
+
# csource will be used to find buggy source text
|
| 344 |
+
return ast, macros, csource
|
| 345 |
+
|
| 346 |
+
def _convert_pycparser_error(self, e, csource):
|
| 347 |
+
# xxx look for "<cdef source string>:NUM:" at the start of str(e)
|
| 348 |
+
# and interpret that as a line number. This will not work if
|
| 349 |
+
# the user gives explicit ``# NUM "FILE"`` directives.
|
| 350 |
+
line = None
|
| 351 |
+
msg = str(e)
|
| 352 |
+
match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg)
|
| 353 |
+
if match:
|
| 354 |
+
linenum = int(match.group(1), 10)
|
| 355 |
+
csourcelines = csource.splitlines()
|
| 356 |
+
if 1 <= linenum <= len(csourcelines):
|
| 357 |
+
line = csourcelines[linenum-1]
|
| 358 |
+
return line
|
| 359 |
+
|
| 360 |
+
def convert_pycparser_error(self, e, csource):
|
| 361 |
+
line = self._convert_pycparser_error(e, csource)
|
| 362 |
+
|
| 363 |
+
msg = str(e)
|
| 364 |
+
if line:
|
| 365 |
+
msg = 'cannot parse "%s"\n%s' % (line.strip(), msg)
|
| 366 |
+
else:
|
| 367 |
+
msg = 'parse error\n%s' % (msg,)
|
| 368 |
+
raise CDefError(msg)
|
| 369 |
+
|
| 370 |
+
def parse(self, csource, override=False, packed=False, pack=None,
|
| 371 |
+
dllexport=False):
|
| 372 |
+
if packed:
|
| 373 |
+
if packed != True:
|
| 374 |
+
raise ValueError("'packed' should be False or True; use "
|
| 375 |
+
"'pack' to give another value")
|
| 376 |
+
if pack:
|
| 377 |
+
raise ValueError("cannot give both 'pack' and 'packed'")
|
| 378 |
+
pack = 1
|
| 379 |
+
elif pack:
|
| 380 |
+
if pack & (pack - 1):
|
| 381 |
+
raise ValueError("'pack' must be a power of two, not %r" %
|
| 382 |
+
(pack,))
|
| 383 |
+
else:
|
| 384 |
+
pack = 0
|
| 385 |
+
prev_options = self._options
|
| 386 |
+
try:
|
| 387 |
+
self._options = {'override': override,
|
| 388 |
+
'packed': pack,
|
| 389 |
+
'dllexport': dllexport}
|
| 390 |
+
self._internal_parse(csource)
|
| 391 |
+
finally:
|
| 392 |
+
self._options = prev_options
|
| 393 |
+
|
| 394 |
+
def _internal_parse(self, csource):
|
| 395 |
+
ast, macros, csource = self._parse(csource)
|
| 396 |
+
# add the macros
|
| 397 |
+
self._process_macros(macros)
|
| 398 |
+
# find the first "__dotdotdot__" and use that as a separator
|
| 399 |
+
# between the repeated typedefs and the real csource
|
| 400 |
+
iterator = iter(ast.ext)
|
| 401 |
+
for decl in iterator:
|
| 402 |
+
if decl.name == '__dotdotdot__':
|
| 403 |
+
break
|
| 404 |
+
else:
|
| 405 |
+
assert 0
|
| 406 |
+
current_decl = None
|
| 407 |
+
#
|
| 408 |
+
try:
|
| 409 |
+
self._inside_extern_python = '__cffi_extern_python_stop'
|
| 410 |
+
for decl in iterator:
|
| 411 |
+
current_decl = decl
|
| 412 |
+
if isinstance(decl, pycparser.c_ast.Decl):
|
| 413 |
+
self._parse_decl(decl)
|
| 414 |
+
elif isinstance(decl, pycparser.c_ast.Typedef):
|
| 415 |
+
if not decl.name:
|
| 416 |
+
raise CDefError("typedef does not declare any name",
|
| 417 |
+
decl)
|
| 418 |
+
quals = 0
|
| 419 |
+
if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType) and
|
| 420 |
+
decl.type.type.names[-1].startswith('__dotdotdot')):
|
| 421 |
+
realtype = self._get_unknown_type(decl)
|
| 422 |
+
elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and
|
| 423 |
+
isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and
|
| 424 |
+
isinstance(decl.type.type.type,
|
| 425 |
+
pycparser.c_ast.IdentifierType) and
|
| 426 |
+
decl.type.type.type.names[-1].startswith('__dotdotdot')):
|
| 427 |
+
realtype = self._get_unknown_ptr_type(decl)
|
| 428 |
+
else:
|
| 429 |
+
realtype, quals = self._get_type_and_quals(
|
| 430 |
+
decl.type, name=decl.name, partial_length_ok=True,
|
| 431 |
+
typedef_example="*(%s *)0" % (decl.name,))
|
| 432 |
+
self._declare('typedef ' + decl.name, realtype, quals=quals)
|
| 433 |
+
elif decl.__class__.__name__ == 'Pragma':
|
| 434 |
+
# skip pragma, only in pycparser 2.15
|
| 435 |
+
import warnings
|
| 436 |
+
warnings.warn(
|
| 437 |
+
"#pragma in cdef() are entirely ignored. "
|
| 438 |
+
"They should be removed for now, otherwise your "
|
| 439 |
+
"code might behave differently in a future version "
|
| 440 |
+
"of CFFI if #pragma support gets added. Note that "
|
| 441 |
+
"'#pragma pack' needs to be replaced with the "
|
| 442 |
+
"'packed' keyword argument to cdef().")
|
| 443 |
+
else:
|
| 444 |
+
raise CDefError("unexpected <%s>: this construct is valid "
|
| 445 |
+
"C but not valid in cdef()" %
|
| 446 |
+
decl.__class__.__name__, decl)
|
| 447 |
+
except CDefError as e:
|
| 448 |
+
if len(e.args) == 1:
|
| 449 |
+
e.args = e.args + (current_decl,)
|
| 450 |
+
raise
|
| 451 |
+
except FFIError as e:
|
| 452 |
+
msg = self._convert_pycparser_error(e, csource)
|
| 453 |
+
if msg:
|
| 454 |
+
e.args = (e.args[0] + "\n *** Err: %s" % msg,)
|
| 455 |
+
raise
|
| 456 |
+
|
| 457 |
+
def _add_constants(self, key, val):
|
| 458 |
+
if key in self._int_constants:
|
| 459 |
+
if self._int_constants[key] == val:
|
| 460 |
+
return # ignore identical double declarations
|
| 461 |
+
raise FFIError(
|
| 462 |
+
"multiple declarations of constant: %s" % (key,))
|
| 463 |
+
self._int_constants[key] = val
|
| 464 |
+
|
| 465 |
+
def _add_integer_constant(self, name, int_str):
|
| 466 |
+
int_str = int_str.lower().rstrip("ul")
|
| 467 |
+
neg = int_str.startswith('-')
|
| 468 |
+
if neg:
|
| 469 |
+
int_str = int_str[1:]
|
| 470 |
+
# "010" is not valid oct in py3
|
| 471 |
+
if (int_str.startswith("0") and int_str != '0'
|
| 472 |
+
and not int_str.startswith("0x")):
|
| 473 |
+
int_str = "0o" + int_str[1:]
|
| 474 |
+
pyvalue = int(int_str, 0)
|
| 475 |
+
if neg:
|
| 476 |
+
pyvalue = -pyvalue
|
| 477 |
+
self._add_constants(name, pyvalue)
|
| 478 |
+
self._declare('macro ' + name, pyvalue)
|
| 479 |
+
|
| 480 |
+
def _process_macros(self, macros):
|
| 481 |
+
for key, value in macros.items():
|
| 482 |
+
value = value.strip()
|
| 483 |
+
if _r_int_literal.match(value):
|
| 484 |
+
self._add_integer_constant(key, value)
|
| 485 |
+
elif value == '...':
|
| 486 |
+
self._declare('macro ' + key, value)
|
| 487 |
+
else:
|
| 488 |
+
raise CDefError(
|
| 489 |
+
'only supports one of the following syntax:\n'
|
| 490 |
+
' #define %s ... (literally dot-dot-dot)\n'
|
| 491 |
+
' #define %s NUMBER (with NUMBER an integer'
|
| 492 |
+
' constant, decimal/hex/octal)\n'
|
| 493 |
+
'got:\n'
|
| 494 |
+
' #define %s %s'
|
| 495 |
+
% (key, key, key, value))
|
| 496 |
+
|
| 497 |
+
def _declare_function(self, tp, quals, decl):
|
| 498 |
+
tp = self._get_type_pointer(tp, quals)
|
| 499 |
+
if self._options.get('dllexport'):
|
| 500 |
+
tag = 'dllexport_python '
|
| 501 |
+
elif self._inside_extern_python == '__cffi_extern_python_start':
|
| 502 |
+
tag = 'extern_python '
|
| 503 |
+
elif self._inside_extern_python == '__cffi_extern_python_plus_c_start':
|
| 504 |
+
tag = 'extern_python_plus_c '
|
| 505 |
+
else:
|
| 506 |
+
tag = 'function '
|
| 507 |
+
self._declare(tag + decl.name, tp)
|
| 508 |
+
|
| 509 |
+
def _parse_decl(self, decl):
|
| 510 |
+
node = decl.type
|
| 511 |
+
if isinstance(node, pycparser.c_ast.FuncDecl):
|
| 512 |
+
tp, quals = self._get_type_and_quals(node, name=decl.name)
|
| 513 |
+
assert isinstance(tp, model.RawFunctionType)
|
| 514 |
+
self._declare_function(tp, quals, decl)
|
| 515 |
+
else:
|
| 516 |
+
if isinstance(node, pycparser.c_ast.Struct):
|
| 517 |
+
self._get_struct_union_enum_type('struct', node)
|
| 518 |
+
elif isinstance(node, pycparser.c_ast.Union):
|
| 519 |
+
self._get_struct_union_enum_type('union', node)
|
| 520 |
+
elif isinstance(node, pycparser.c_ast.Enum):
|
| 521 |
+
self._get_struct_union_enum_type('enum', node)
|
| 522 |
+
elif not decl.name:
|
| 523 |
+
raise CDefError("construct does not declare any variable",
|
| 524 |
+
decl)
|
| 525 |
+
#
|
| 526 |
+
if decl.name:
|
| 527 |
+
tp, quals = self._get_type_and_quals(node,
|
| 528 |
+
partial_length_ok=True)
|
| 529 |
+
if tp.is_raw_function:
|
| 530 |
+
self._declare_function(tp, quals, decl)
|
| 531 |
+
elif (tp.is_integer_type() and
|
| 532 |
+
hasattr(decl, 'init') and
|
| 533 |
+
hasattr(decl.init, 'value') and
|
| 534 |
+
_r_int_literal.match(decl.init.value)):
|
| 535 |
+
self._add_integer_constant(decl.name, decl.init.value)
|
| 536 |
+
elif (tp.is_integer_type() and
|
| 537 |
+
isinstance(decl.init, pycparser.c_ast.UnaryOp) and
|
| 538 |
+
decl.init.op == '-' and
|
| 539 |
+
hasattr(decl.init.expr, 'value') and
|
| 540 |
+
_r_int_literal.match(decl.init.expr.value)):
|
| 541 |
+
self._add_integer_constant(decl.name,
|
| 542 |
+
'-' + decl.init.expr.value)
|
| 543 |
+
elif (tp is model.void_type and
|
| 544 |
+
decl.name.startswith('__cffi_extern_python_')):
|
| 545 |
+
# hack: `extern "Python"` in the C source is replaced
|
| 546 |
+
# with "void __cffi_extern_python_start;" and
|
| 547 |
+
# "void __cffi_extern_python_stop;"
|
| 548 |
+
self._inside_extern_python = decl.name
|
| 549 |
+
else:
|
| 550 |
+
if self._inside_extern_python !='__cffi_extern_python_stop':
|
| 551 |
+
raise CDefError(
|
| 552 |
+
"cannot declare constants or "
|
| 553 |
+
"variables with 'extern \"Python\"'")
|
| 554 |
+
if (quals & model.Q_CONST) and not tp.is_array_type:
|
| 555 |
+
self._declare('constant ' + decl.name, tp, quals=quals)
|
| 556 |
+
else:
|
| 557 |
+
_warn_for_non_extern_non_static_global_variable(decl)
|
| 558 |
+
self._declare('variable ' + decl.name, tp, quals=quals)
|
| 559 |
+
|
| 560 |
+
def parse_type(self, cdecl):
|
| 561 |
+
return self.parse_type_and_quals(cdecl)[0]
|
| 562 |
+
|
| 563 |
+
def parse_type_and_quals(self, cdecl):
|
| 564 |
+
ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2]
|
| 565 |
+
assert not macros
|
| 566 |
+
exprnode = ast.ext[-1].type.args.params[0]
|
| 567 |
+
if isinstance(exprnode, pycparser.c_ast.ID):
|
| 568 |
+
raise CDefError("unknown identifier '%s'" % (exprnode.name,))
|
| 569 |
+
return self._get_type_and_quals(exprnode.type)
|
| 570 |
+
|
| 571 |
+
def _declare(self, name, obj, included=False, quals=0):
|
| 572 |
+
if name in self._declarations:
|
| 573 |
+
prevobj, prevquals = self._declarations[name]
|
| 574 |
+
if prevobj is obj and prevquals == quals:
|
| 575 |
+
return
|
| 576 |
+
if not self._options.get('override'):
|
| 577 |
+
raise FFIError(
|
| 578 |
+
"multiple declarations of %s (for interactive usage, "
|
| 579 |
+
"try cdef(xx, override=True))" % (name,))
|
| 580 |
+
assert '__dotdotdot__' not in name.split()
|
| 581 |
+
self._declarations[name] = (obj, quals)
|
| 582 |
+
if included:
|
| 583 |
+
self._included_declarations.add(obj)
|
| 584 |
+
|
| 585 |
+
def _extract_quals(self, type):
|
| 586 |
+
quals = 0
|
| 587 |
+
if isinstance(type, (pycparser.c_ast.TypeDecl,
|
| 588 |
+
pycparser.c_ast.PtrDecl)):
|
| 589 |
+
if 'const' in type.quals:
|
| 590 |
+
quals |= model.Q_CONST
|
| 591 |
+
if 'volatile' in type.quals:
|
| 592 |
+
quals |= model.Q_VOLATILE
|
| 593 |
+
if 'restrict' in type.quals:
|
| 594 |
+
quals |= model.Q_RESTRICT
|
| 595 |
+
return quals
|
| 596 |
+
|
| 597 |
+
def _get_type_pointer(self, type, quals, declname=None):
|
| 598 |
+
if isinstance(type, model.RawFunctionType):
|
| 599 |
+
return type.as_function_pointer()
|
| 600 |
+
if (isinstance(type, model.StructOrUnionOrEnum) and
|
| 601 |
+
type.name.startswith('$') and type.name[1:].isdigit() and
|
| 602 |
+
type.forcename is None and declname is not None):
|
| 603 |
+
return model.NamedPointerType(type, declname, quals)
|
| 604 |
+
return model.PointerType(type, quals)
|
| 605 |
+
|
| 606 |
+
def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False,
|
| 607 |
+
typedef_example=None):
|
| 608 |
+
# first, dereference typedefs, if we have it already parsed, we're good
|
| 609 |
+
if (isinstance(typenode, pycparser.c_ast.TypeDecl) and
|
| 610 |
+
isinstance(typenode.type, pycparser.c_ast.IdentifierType) and
|
| 611 |
+
len(typenode.type.names) == 1 and
|
| 612 |
+
('typedef ' + typenode.type.names[0]) in self._declarations):
|
| 613 |
+
tp, quals = self._declarations['typedef ' + typenode.type.names[0]]
|
| 614 |
+
quals |= self._extract_quals(typenode)
|
| 615 |
+
return tp, quals
|
| 616 |
+
#
|
| 617 |
+
if isinstance(typenode, pycparser.c_ast.ArrayDecl):
|
| 618 |
+
# array type
|
| 619 |
+
if typenode.dim is None:
|
| 620 |
+
length = None
|
| 621 |
+
else:
|
| 622 |
+
length = self._parse_constant(
|
| 623 |
+
typenode.dim, partial_length_ok=partial_length_ok)
|
| 624 |
+
# a hack: in 'typedef int foo_t[...][...];', don't use '...' as
|
| 625 |
+
# the length but use directly the C expression that would be
|
| 626 |
+
# generated by recompiler.py. This lets the typedef be used in
|
| 627 |
+
# many more places within recompiler.py
|
| 628 |
+
if typedef_example is not None:
|
| 629 |
+
if length == '...':
|
| 630 |
+
length = '_cffi_array_len(%s)' % (typedef_example,)
|
| 631 |
+
typedef_example = "*" + typedef_example
|
| 632 |
+
#
|
| 633 |
+
tp, quals = self._get_type_and_quals(typenode.type,
|
| 634 |
+
partial_length_ok=partial_length_ok,
|
| 635 |
+
typedef_example=typedef_example)
|
| 636 |
+
return model.ArrayType(tp, length), quals
|
| 637 |
+
#
|
| 638 |
+
if isinstance(typenode, pycparser.c_ast.PtrDecl):
|
| 639 |
+
# pointer type
|
| 640 |
+
itemtype, itemquals = self._get_type_and_quals(typenode.type)
|
| 641 |
+
tp = self._get_type_pointer(itemtype, itemquals, declname=name)
|
| 642 |
+
quals = self._extract_quals(typenode)
|
| 643 |
+
return tp, quals
|
| 644 |
+
#
|
| 645 |
+
if isinstance(typenode, pycparser.c_ast.TypeDecl):
|
| 646 |
+
quals = self._extract_quals(typenode)
|
| 647 |
+
type = typenode.type
|
| 648 |
+
if isinstance(type, pycparser.c_ast.IdentifierType):
|
| 649 |
+
# assume a primitive type. get it from .names, but reduce
|
| 650 |
+
# synonyms to a single chosen combination
|
| 651 |
+
names = list(type.names)
|
| 652 |
+
if names != ['signed', 'char']: # keep this unmodified
|
| 653 |
+
prefixes = {}
|
| 654 |
+
while names:
|
| 655 |
+
name = names[0]
|
| 656 |
+
if name in ('short', 'long', 'signed', 'unsigned'):
|
| 657 |
+
prefixes[name] = prefixes.get(name, 0) + 1
|
| 658 |
+
del names[0]
|
| 659 |
+
else:
|
| 660 |
+
break
|
| 661 |
+
# ignore the 'signed' prefix below, and reorder the others
|
| 662 |
+
newnames = []
|
| 663 |
+
for prefix in ('unsigned', 'short', 'long'):
|
| 664 |
+
for i in range(prefixes.get(prefix, 0)):
|
| 665 |
+
newnames.append(prefix)
|
| 666 |
+
if not names:
|
| 667 |
+
names = ['int'] # implicitly
|
| 668 |
+
if names == ['int']: # but kill it if 'short' or 'long'
|
| 669 |
+
if 'short' in prefixes or 'long' in prefixes:
|
| 670 |
+
names = []
|
| 671 |
+
names = newnames + names
|
| 672 |
+
ident = ' '.join(names)
|
| 673 |
+
if ident == 'void':
|
| 674 |
+
return model.void_type, quals
|
| 675 |
+
if ident == '__dotdotdot__':
|
| 676 |
+
raise FFIError(':%d: bad usage of "..."' %
|
| 677 |
+
typenode.coord.line)
|
| 678 |
+
tp0, quals0 = resolve_common_type(self, ident)
|
| 679 |
+
return tp0, (quals | quals0)
|
| 680 |
+
#
|
| 681 |
+
if isinstance(type, pycparser.c_ast.Struct):
|
| 682 |
+
# 'struct foobar'
|
| 683 |
+
tp = self._get_struct_union_enum_type('struct', type, name)
|
| 684 |
+
return tp, quals
|
| 685 |
+
#
|
| 686 |
+
if isinstance(type, pycparser.c_ast.Union):
|
| 687 |
+
# 'union foobar'
|
| 688 |
+
tp = self._get_struct_union_enum_type('union', type, name)
|
| 689 |
+
return tp, quals
|
| 690 |
+
#
|
| 691 |
+
if isinstance(type, pycparser.c_ast.Enum):
|
| 692 |
+
# 'enum foobar'
|
| 693 |
+
tp = self._get_struct_union_enum_type('enum', type, name)
|
| 694 |
+
return tp, quals
|
| 695 |
+
#
|
| 696 |
+
if isinstance(typenode, pycparser.c_ast.FuncDecl):
|
| 697 |
+
# a function type
|
| 698 |
+
return self._parse_function_type(typenode, name), 0
|
| 699 |
+
#
|
| 700 |
+
# nested anonymous structs or unions end up here
|
| 701 |
+
if isinstance(typenode, pycparser.c_ast.Struct):
|
| 702 |
+
return self._get_struct_union_enum_type('struct', typenode, name,
|
| 703 |
+
nested=True), 0
|
| 704 |
+
if isinstance(typenode, pycparser.c_ast.Union):
|
| 705 |
+
return self._get_struct_union_enum_type('union', typenode, name,
|
| 706 |
+
nested=True), 0
|
| 707 |
+
#
|
| 708 |
+
raise FFIError(":%d: bad or unsupported type declaration" %
|
| 709 |
+
typenode.coord.line)
|
| 710 |
+
|
| 711 |
+
def _parse_function_type(self, typenode, funcname=None):
|
| 712 |
+
params = list(getattr(typenode.args, 'params', []))
|
| 713 |
+
for i, arg in enumerate(params):
|
| 714 |
+
if not hasattr(arg, 'type'):
|
| 715 |
+
raise CDefError("%s arg %d: unknown type '%s'"
|
| 716 |
+
" (if you meant to use the old C syntax of giving"
|
| 717 |
+
" untyped arguments, it is not supported)"
|
| 718 |
+
% (funcname or 'in expression', i + 1,
|
| 719 |
+
getattr(arg, 'name', '?')))
|
| 720 |
+
ellipsis = (
|
| 721 |
+
len(params) > 0 and
|
| 722 |
+
isinstance(params[-1].type, pycparser.c_ast.TypeDecl) and
|
| 723 |
+
isinstance(params[-1].type.type,
|
| 724 |
+
pycparser.c_ast.IdentifierType) and
|
| 725 |
+
params[-1].type.type.names == ['__dotdotdot__'])
|
| 726 |
+
if ellipsis:
|
| 727 |
+
params.pop()
|
| 728 |
+
if not params:
|
| 729 |
+
raise CDefError(
|
| 730 |
+
"%s: a function with only '(...)' as argument"
|
| 731 |
+
" is not correct C" % (funcname or 'in expression'))
|
| 732 |
+
args = [self._as_func_arg(*self._get_type_and_quals(argdeclnode.type))
|
| 733 |
+
for argdeclnode in params]
|
| 734 |
+
if not ellipsis and args == [model.void_type]:
|
| 735 |
+
args = []
|
| 736 |
+
result, quals = self._get_type_and_quals(typenode.type)
|
| 737 |
+
# the 'quals' on the result type are ignored. HACK: we absure them
|
| 738 |
+
# to detect __stdcall functions: we textually replace "__stdcall"
|
| 739 |
+
# with "volatile volatile const" above.
|
| 740 |
+
abi = None
|
| 741 |
+
if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway
|
| 742 |
+
if typenode.type.quals[-3:] == ['volatile', 'volatile', 'const']:
|
| 743 |
+
abi = '__stdcall'
|
| 744 |
+
return model.RawFunctionType(tuple(args), result, ellipsis, abi)
|
| 745 |
+
|
| 746 |
+
def _as_func_arg(self, type, quals):
|
| 747 |
+
if isinstance(type, model.ArrayType):
|
| 748 |
+
return model.PointerType(type.item, quals)
|
| 749 |
+
elif isinstance(type, model.RawFunctionType):
|
| 750 |
+
return type.as_function_pointer()
|
| 751 |
+
else:
|
| 752 |
+
return type
|
| 753 |
+
|
| 754 |
+
def _get_struct_union_enum_type(self, kind, type, name=None, nested=False):
|
| 755 |
+
# First, a level of caching on the exact 'type' node of the AST.
|
| 756 |
+
# This is obscure, but needed because pycparser "unrolls" declarations
|
| 757 |
+
# such as "typedef struct { } foo_t, *foo_p" and we end up with
|
| 758 |
+
# an AST that is not a tree, but a DAG, with the "type" node of the
|
| 759 |
+
# two branches foo_t and foo_p of the trees being the same node.
|
| 760 |
+
# It's a bit silly but detecting "DAG-ness" in the AST tree seems
|
| 761 |
+
# to be the only way to distinguish this case from two independent
|
| 762 |
+
# structs. See test_struct_with_two_usages.
|
| 763 |
+
try:
|
| 764 |
+
return self._structnode2type[type]
|
| 765 |
+
except KeyError:
|
| 766 |
+
pass
|
| 767 |
+
#
|
| 768 |
+
# Note that this must handle parsing "struct foo" any number of
|
| 769 |
+
# times and always return the same StructType object. Additionally,
|
| 770 |
+
# one of these times (not necessarily the first), the fields of
|
| 771 |
+
# the struct can be specified with "struct foo { ...fields... }".
|
| 772 |
+
# If no name is given, then we have to create a new anonymous struct
|
| 773 |
+
# with no caching; in this case, the fields are either specified
|
| 774 |
+
# right now or never.
|
| 775 |
+
#
|
| 776 |
+
force_name = name
|
| 777 |
+
name = type.name
|
| 778 |
+
#
|
| 779 |
+
# get the type or create it if needed
|
| 780 |
+
if name is None:
|
| 781 |
+
# 'force_name' is used to guess a more readable name for
|
| 782 |
+
# anonymous structs, for the common case "typedef struct { } foo".
|
| 783 |
+
if force_name is not None:
|
| 784 |
+
explicit_name = '$%s' % force_name
|
| 785 |
+
else:
|
| 786 |
+
self._anonymous_counter += 1
|
| 787 |
+
explicit_name = '$%d' % self._anonymous_counter
|
| 788 |
+
tp = None
|
| 789 |
+
else:
|
| 790 |
+
explicit_name = name
|
| 791 |
+
key = '%s %s' % (kind, name)
|
| 792 |
+
tp, _ = self._declarations.get(key, (None, None))
|
| 793 |
+
#
|
| 794 |
+
if tp is None:
|
| 795 |
+
if kind == 'struct':
|
| 796 |
+
tp = model.StructType(explicit_name, None, None, None)
|
| 797 |
+
elif kind == 'union':
|
| 798 |
+
tp = model.UnionType(explicit_name, None, None, None)
|
| 799 |
+
elif kind == 'enum':
|
| 800 |
+
if explicit_name == '__dotdotdot__':
|
| 801 |
+
raise CDefError("Enums cannot be declared with ...")
|
| 802 |
+
tp = self._build_enum_type(explicit_name, type.values)
|
| 803 |
+
else:
|
| 804 |
+
raise AssertionError("kind = %r" % (kind,))
|
| 805 |
+
if name is not None:
|
| 806 |
+
self._declare(key, tp)
|
| 807 |
+
else:
|
| 808 |
+
if kind == 'enum' and type.values is not None:
|
| 809 |
+
raise NotImplementedError(
|
| 810 |
+
"enum %s: the '{}' declaration should appear on the first "
|
| 811 |
+
"time the enum is mentioned, not later" % explicit_name)
|
| 812 |
+
if not tp.forcename:
|
| 813 |
+
tp.force_the_name(force_name)
|
| 814 |
+
if tp.forcename and '$' in tp.name:
|
| 815 |
+
self._declare('anonymous %s' % tp.forcename, tp)
|
| 816 |
+
#
|
| 817 |
+
self._structnode2type[type] = tp
|
| 818 |
+
#
|
| 819 |
+
# enums: done here
|
| 820 |
+
if kind == 'enum':
|
| 821 |
+
return tp
|
| 822 |
+
#
|
| 823 |
+
# is there a 'type.decls'? If yes, then this is the place in the
|
| 824 |
+
# C sources that declare the fields. If no, then just return the
|
| 825 |
+
# existing type, possibly still incomplete.
|
| 826 |
+
if type.decls is None:
|
| 827 |
+
return tp
|
| 828 |
+
#
|
| 829 |
+
if tp.fldnames is not None:
|
| 830 |
+
raise CDefError("duplicate declaration of struct %s" % name)
|
| 831 |
+
fldnames = []
|
| 832 |
+
fldtypes = []
|
| 833 |
+
fldbitsize = []
|
| 834 |
+
fldquals = []
|
| 835 |
+
for decl in type.decls:
|
| 836 |
+
if (isinstance(decl.type, pycparser.c_ast.IdentifierType) and
|
| 837 |
+
''.join(decl.type.names) == '__dotdotdot__'):
|
| 838 |
+
# XXX pycparser is inconsistent: 'names' should be a list
|
| 839 |
+
# of strings, but is sometimes just one string. Use
|
| 840 |
+
# str.join() as a way to cope with both.
|
| 841 |
+
self._make_partial(tp, nested)
|
| 842 |
+
continue
|
| 843 |
+
if decl.bitsize is None:
|
| 844 |
+
bitsize = -1
|
| 845 |
+
else:
|
| 846 |
+
bitsize = self._parse_constant(decl.bitsize)
|
| 847 |
+
self._partial_length = False
|
| 848 |
+
type, fqual = self._get_type_and_quals(decl.type,
|
| 849 |
+
partial_length_ok=True)
|
| 850 |
+
if self._partial_length:
|
| 851 |
+
self._make_partial(tp, nested)
|
| 852 |
+
if isinstance(type, model.StructType) and type.partial:
|
| 853 |
+
self._make_partial(tp, nested)
|
| 854 |
+
fldnames.append(decl.name or '')
|
| 855 |
+
fldtypes.append(type)
|
| 856 |
+
fldbitsize.append(bitsize)
|
| 857 |
+
fldquals.append(fqual)
|
| 858 |
+
tp.fldnames = tuple(fldnames)
|
| 859 |
+
tp.fldtypes = tuple(fldtypes)
|
| 860 |
+
tp.fldbitsize = tuple(fldbitsize)
|
| 861 |
+
tp.fldquals = tuple(fldquals)
|
| 862 |
+
if fldbitsize != [-1] * len(fldbitsize):
|
| 863 |
+
if isinstance(tp, model.StructType) and tp.partial:
|
| 864 |
+
raise NotImplementedError("%s: using both bitfields and '...;'"
|
| 865 |
+
% (tp,))
|
| 866 |
+
tp.packed = self._options.get('packed')
|
| 867 |
+
if tp.completed: # must be re-completed: it is not opaque any more
|
| 868 |
+
tp.completed = 0
|
| 869 |
+
self._recomplete.append(tp)
|
| 870 |
+
return tp
|
| 871 |
+
|
| 872 |
+
def _make_partial(self, tp, nested):
|
| 873 |
+
if not isinstance(tp, model.StructOrUnion):
|
| 874 |
+
raise CDefError("%s cannot be partial" % (tp,))
|
| 875 |
+
if not tp.has_c_name() and not nested:
|
| 876 |
+
raise NotImplementedError("%s is partial but has no C name" %(tp,))
|
| 877 |
+
tp.partial = True
|
| 878 |
+
|
| 879 |
+
def _parse_constant(self, exprnode, partial_length_ok=False):
|
| 880 |
+
# for now, limited to expressions that are an immediate number
|
| 881 |
+
# or positive/negative number
|
| 882 |
+
if isinstance(exprnode, pycparser.c_ast.Constant):
|
| 883 |
+
s = exprnode.value
|
| 884 |
+
if '0' <= s[0] <= '9':
|
| 885 |
+
s = s.rstrip('uUlL')
|
| 886 |
+
try:
|
| 887 |
+
if s.startswith('0'):
|
| 888 |
+
return int(s, 8)
|
| 889 |
+
else:
|
| 890 |
+
return int(s, 10)
|
| 891 |
+
except ValueError:
|
| 892 |
+
if len(s) > 1:
|
| 893 |
+
if s.lower()[0:2] == '0x':
|
| 894 |
+
return int(s, 16)
|
| 895 |
+
elif s.lower()[0:2] == '0b':
|
| 896 |
+
return int(s, 2)
|
| 897 |
+
raise CDefError("invalid constant %r" % (s,))
|
| 898 |
+
elif s[0] == "'" and s[-1] == "'" and (
|
| 899 |
+
len(s) == 3 or (len(s) == 4 and s[1] == "\\")):
|
| 900 |
+
return ord(s[-2])
|
| 901 |
+
else:
|
| 902 |
+
raise CDefError("invalid constant %r" % (s,))
|
| 903 |
+
#
|
| 904 |
+
if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
|
| 905 |
+
exprnode.op == '+'):
|
| 906 |
+
return self._parse_constant(exprnode.expr)
|
| 907 |
+
#
|
| 908 |
+
if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
|
| 909 |
+
exprnode.op == '-'):
|
| 910 |
+
return -self._parse_constant(exprnode.expr)
|
| 911 |
+
# load previously defined int constant
|
| 912 |
+
if (isinstance(exprnode, pycparser.c_ast.ID) and
|
| 913 |
+
exprnode.name in self._int_constants):
|
| 914 |
+
return self._int_constants[exprnode.name]
|
| 915 |
+
#
|
| 916 |
+
if (isinstance(exprnode, pycparser.c_ast.ID) and
|
| 917 |
+
exprnode.name == '__dotdotdotarray__'):
|
| 918 |
+
if partial_length_ok:
|
| 919 |
+
self._partial_length = True
|
| 920 |
+
return '...'
|
| 921 |
+
raise FFIError(":%d: unsupported '[...]' here, cannot derive "
|
| 922 |
+
"the actual array length in this context"
|
| 923 |
+
% exprnode.coord.line)
|
| 924 |
+
#
|
| 925 |
+
if isinstance(exprnode, pycparser.c_ast.BinaryOp):
|
| 926 |
+
left = self._parse_constant(exprnode.left)
|
| 927 |
+
right = self._parse_constant(exprnode.right)
|
| 928 |
+
if exprnode.op == '+':
|
| 929 |
+
return left + right
|
| 930 |
+
elif exprnode.op == '-':
|
| 931 |
+
return left - right
|
| 932 |
+
elif exprnode.op == '*':
|
| 933 |
+
return left * right
|
| 934 |
+
elif exprnode.op == '/':
|
| 935 |
+
return self._c_div(left, right)
|
| 936 |
+
elif exprnode.op == '%':
|
| 937 |
+
return left - self._c_div(left, right) * right
|
| 938 |
+
elif exprnode.op == '<<':
|
| 939 |
+
return left << right
|
| 940 |
+
elif exprnode.op == '>>':
|
| 941 |
+
return left >> right
|
| 942 |
+
elif exprnode.op == '&':
|
| 943 |
+
return left & right
|
| 944 |
+
elif exprnode.op == '|':
|
| 945 |
+
return left | right
|
| 946 |
+
elif exprnode.op == '^':
|
| 947 |
+
return left ^ right
|
| 948 |
+
#
|
| 949 |
+
raise FFIError(":%d: unsupported expression: expected a "
|
| 950 |
+
"simple numeric constant" % exprnode.coord.line)
|
| 951 |
+
|
| 952 |
+
def _c_div(self, a, b):
|
| 953 |
+
result = a // b
|
| 954 |
+
if ((a < 0) ^ (b < 0)) and (a % b) != 0:
|
| 955 |
+
result += 1
|
| 956 |
+
return result
|
| 957 |
+
|
| 958 |
+
def _build_enum_type(self, explicit_name, decls):
|
| 959 |
+
if decls is not None:
|
| 960 |
+
partial = False
|
| 961 |
+
enumerators = []
|
| 962 |
+
enumvalues = []
|
| 963 |
+
nextenumvalue = 0
|
| 964 |
+
for enum in decls.enumerators:
|
| 965 |
+
if _r_enum_dotdotdot.match(enum.name):
|
| 966 |
+
partial = True
|
| 967 |
+
continue
|
| 968 |
+
if enum.value is not None:
|
| 969 |
+
nextenumvalue = self._parse_constant(enum.value)
|
| 970 |
+
enumerators.append(enum.name)
|
| 971 |
+
enumvalues.append(nextenumvalue)
|
| 972 |
+
self._add_constants(enum.name, nextenumvalue)
|
| 973 |
+
nextenumvalue += 1
|
| 974 |
+
enumerators = tuple(enumerators)
|
| 975 |
+
enumvalues = tuple(enumvalues)
|
| 976 |
+
tp = model.EnumType(explicit_name, enumerators, enumvalues)
|
| 977 |
+
tp.partial = partial
|
| 978 |
+
else: # opaque enum
|
| 979 |
+
tp = model.EnumType(explicit_name, (), ())
|
| 980 |
+
return tp
|
| 981 |
+
|
| 982 |
+
def include(self, other):
|
| 983 |
+
for name, (tp, quals) in other._declarations.items():
|
| 984 |
+
if name.startswith('anonymous $enum_$'):
|
| 985 |
+
continue # fix for test_anonymous_enum_include
|
| 986 |
+
kind = name.split(' ', 1)[0]
|
| 987 |
+
if kind in ('struct', 'union', 'enum', 'anonymous', 'typedef'):
|
| 988 |
+
self._declare(name, tp, included=True, quals=quals)
|
| 989 |
+
for k, v in other._int_constants.items():
|
| 990 |
+
self._add_constants(k, v)
|
| 991 |
+
|
| 992 |
+
def _get_unknown_type(self, decl):
|
| 993 |
+
typenames = decl.type.type.names
|
| 994 |
+
if typenames == ['__dotdotdot__']:
|
| 995 |
+
return model.unknown_type(decl.name)
|
| 996 |
+
|
| 997 |
+
if typenames == ['__dotdotdotint__']:
|
| 998 |
+
if self._uses_new_feature is None:
|
| 999 |
+
self._uses_new_feature = "'typedef int... %s'" % decl.name
|
| 1000 |
+
return model.UnknownIntegerType(decl.name)
|
| 1001 |
+
|
| 1002 |
+
if typenames == ['__dotdotdotfloat__']:
|
| 1003 |
+
# note: not for 'long double' so far
|
| 1004 |
+
if self._uses_new_feature is None:
|
| 1005 |
+
self._uses_new_feature = "'typedef float... %s'" % decl.name
|
| 1006 |
+
return model.UnknownFloatType(decl.name)
|
| 1007 |
+
|
| 1008 |
+
raise FFIError(':%d: unsupported usage of "..." in typedef'
|
| 1009 |
+
% decl.coord.line)
|
| 1010 |
+
|
| 1011 |
+
def _get_unknown_ptr_type(self, decl):
|
| 1012 |
+
if decl.type.type.type.names == ['__dotdotdot__']:
|
| 1013 |
+
return model.unknown_ptr_type(decl.name)
|
| 1014 |
+
raise FFIError(':%d: unsupported usage of "..." in typedef'
|
| 1015 |
+
% decl.coord.line)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/error.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
class FFIError(Exception):
|
| 3 |
+
__module__ = 'cffi'
|
| 4 |
+
|
| 5 |
+
class CDefError(Exception):
|
| 6 |
+
__module__ = 'cffi'
|
| 7 |
+
def __str__(self):
|
| 8 |
+
try:
|
| 9 |
+
current_decl = self.args[1]
|
| 10 |
+
filename = current_decl.coord.file
|
| 11 |
+
linenum = current_decl.coord.line
|
| 12 |
+
prefix = '%s:%d: ' % (filename, linenum)
|
| 13 |
+
except (AttributeError, TypeError, IndexError):
|
| 14 |
+
prefix = ''
|
| 15 |
+
return '%s%s' % (prefix, self.args[0])
|
| 16 |
+
|
| 17 |
+
class VerificationError(Exception):
|
| 18 |
+
""" An error raised when verification fails
|
| 19 |
+
"""
|
| 20 |
+
__module__ = 'cffi'
|
| 21 |
+
|
| 22 |
+
class VerificationMissing(Exception):
|
| 23 |
+
""" An error raised when incomplete structures are passed into
|
| 24 |
+
cdef, but no verification has been done
|
| 25 |
+
"""
|
| 26 |
+
__module__ = 'cffi'
|
| 27 |
+
|
| 28 |
+
class PkgConfigError(Exception):
|
| 29 |
+
""" An error raised for missing modules in pkg-config
|
| 30 |
+
"""
|
| 31 |
+
__module__ = 'cffi'
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/ffiplatform.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys, os
|
| 2 |
+
from .error import VerificationError
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
LIST_OF_FILE_NAMES = ['sources', 'include_dirs', 'library_dirs',
|
| 6 |
+
'extra_objects', 'depends']
|
| 7 |
+
|
| 8 |
+
def get_extension(srcfilename, modname, sources=(), **kwds):
|
| 9 |
+
from cffi._shimmed_dist_utils import Extension
|
| 10 |
+
allsources = [srcfilename]
|
| 11 |
+
for src in sources:
|
| 12 |
+
allsources.append(os.path.normpath(src))
|
| 13 |
+
return Extension(name=modname, sources=allsources, **kwds)
|
| 14 |
+
|
| 15 |
+
def compile(tmpdir, ext, compiler_verbose=0, debug=None):
|
| 16 |
+
"""Compile a C extension module using distutils."""
|
| 17 |
+
|
| 18 |
+
saved_environ = os.environ.copy()
|
| 19 |
+
try:
|
| 20 |
+
outputfilename = _build(tmpdir, ext, compiler_verbose, debug)
|
| 21 |
+
outputfilename = os.path.abspath(outputfilename)
|
| 22 |
+
finally:
|
| 23 |
+
# workaround for a distutils bugs where some env vars can
|
| 24 |
+
# become longer and longer every time it is used
|
| 25 |
+
for key, value in saved_environ.items():
|
| 26 |
+
if os.environ.get(key) != value:
|
| 27 |
+
os.environ[key] = value
|
| 28 |
+
return outputfilename
|
| 29 |
+
|
| 30 |
+
def _build(tmpdir, ext, compiler_verbose=0, debug=None):
|
| 31 |
+
# XXX compact but horrible :-(
|
| 32 |
+
from cffi._shimmed_dist_utils import Distribution, CompileError, LinkError, set_threshold, set_verbosity
|
| 33 |
+
|
| 34 |
+
dist = Distribution({'ext_modules': [ext]})
|
| 35 |
+
dist.parse_config_files()
|
| 36 |
+
options = dist.get_option_dict('build_ext')
|
| 37 |
+
if debug is None:
|
| 38 |
+
debug = sys.flags.debug
|
| 39 |
+
options['debug'] = ('ffiplatform', debug)
|
| 40 |
+
options['force'] = ('ffiplatform', True)
|
| 41 |
+
options['build_lib'] = ('ffiplatform', tmpdir)
|
| 42 |
+
options['build_temp'] = ('ffiplatform', tmpdir)
|
| 43 |
+
#
|
| 44 |
+
try:
|
| 45 |
+
old_level = set_threshold(0) or 0
|
| 46 |
+
try:
|
| 47 |
+
set_verbosity(compiler_verbose)
|
| 48 |
+
dist.run_command('build_ext')
|
| 49 |
+
cmd_obj = dist.get_command_obj('build_ext')
|
| 50 |
+
[soname] = cmd_obj.get_outputs()
|
| 51 |
+
finally:
|
| 52 |
+
set_threshold(old_level)
|
| 53 |
+
except (CompileError, LinkError) as e:
|
| 54 |
+
raise VerificationError('%s: %s' % (e.__class__.__name__, e))
|
| 55 |
+
#
|
| 56 |
+
return soname
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
from os.path import samefile
|
| 60 |
+
except ImportError:
|
| 61 |
+
def samefile(f1, f2):
|
| 62 |
+
return os.path.abspath(f1) == os.path.abspath(f2)
|
| 63 |
+
|
| 64 |
+
def maybe_relative_path(path):
|
| 65 |
+
if not os.path.isabs(path):
|
| 66 |
+
return path # already relative
|
| 67 |
+
dir = path
|
| 68 |
+
names = []
|
| 69 |
+
while True:
|
| 70 |
+
prevdir = dir
|
| 71 |
+
dir, name = os.path.split(prevdir)
|
| 72 |
+
if dir == prevdir or not dir:
|
| 73 |
+
return path # failed to make it relative
|
| 74 |
+
names.append(name)
|
| 75 |
+
try:
|
| 76 |
+
if samefile(dir, os.curdir):
|
| 77 |
+
names.reverse()
|
| 78 |
+
return os.path.join(*names)
|
| 79 |
+
except OSError:
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
# ____________________________________________________________
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
int_or_long = (int, long)
|
| 86 |
+
import cStringIO
|
| 87 |
+
except NameError:
|
| 88 |
+
int_or_long = int # Python 3
|
| 89 |
+
import io as cStringIO
|
| 90 |
+
|
| 91 |
+
def _flatten(x, f):
|
| 92 |
+
if isinstance(x, str):
|
| 93 |
+
f.write('%ds%s' % (len(x), x))
|
| 94 |
+
elif isinstance(x, dict):
|
| 95 |
+
keys = sorted(x.keys())
|
| 96 |
+
f.write('%dd' % len(keys))
|
| 97 |
+
for key in keys:
|
| 98 |
+
_flatten(key, f)
|
| 99 |
+
_flatten(x[key], f)
|
| 100 |
+
elif isinstance(x, (list, tuple)):
|
| 101 |
+
f.write('%dl' % len(x))
|
| 102 |
+
for value in x:
|
| 103 |
+
_flatten(value, f)
|
| 104 |
+
elif isinstance(x, int_or_long):
|
| 105 |
+
f.write('%di' % (x,))
|
| 106 |
+
else:
|
| 107 |
+
raise TypeError(
|
| 108 |
+
"the keywords to verify() contains unsupported object %r" % (x,))
|
| 109 |
+
|
| 110 |
+
def flatten(x):
|
| 111 |
+
f = cStringIO.StringIO()
|
| 112 |
+
_flatten(x, f)
|
| 113 |
+
return f.getvalue()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/lock.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
if sys.version_info < (3,):
|
| 4 |
+
try:
|
| 5 |
+
from thread import allocate_lock
|
| 6 |
+
except ImportError:
|
| 7 |
+
from dummy_thread import allocate_lock
|
| 8 |
+
else:
|
| 9 |
+
try:
|
| 10 |
+
from _thread import allocate_lock
|
| 11 |
+
except ImportError:
|
| 12 |
+
from _dummy_thread import allocate_lock
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
##import sys
|
| 16 |
+
##l1 = allocate_lock
|
| 17 |
+
|
| 18 |
+
##class allocate_lock(object):
|
| 19 |
+
## def __init__(self):
|
| 20 |
+
## self._real = l1()
|
| 21 |
+
## def __enter__(self):
|
| 22 |
+
## for i in range(4, 0, -1):
|
| 23 |
+
## print sys._getframe(i).f_code
|
| 24 |
+
## print
|
| 25 |
+
## return self._real.__enter__()
|
| 26 |
+
## def __exit__(self, *args):
|
| 27 |
+
## return self._real.__exit__(*args)
|
| 28 |
+
## def acquire(self, f):
|
| 29 |
+
## assert f is False
|
| 30 |
+
## return self._real.acquire(f)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/model.py
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import types
|
| 2 |
+
import weakref
|
| 3 |
+
|
| 4 |
+
from .lock import allocate_lock
|
| 5 |
+
from .error import CDefError, VerificationError, VerificationMissing
|
| 6 |
+
|
| 7 |
+
# type qualifiers
|
| 8 |
+
Q_CONST = 0x01
|
| 9 |
+
Q_RESTRICT = 0x02
|
| 10 |
+
Q_VOLATILE = 0x04
|
| 11 |
+
|
| 12 |
+
def qualify(quals, replace_with):
|
| 13 |
+
if quals & Q_CONST:
|
| 14 |
+
replace_with = ' const ' + replace_with.lstrip()
|
| 15 |
+
if quals & Q_VOLATILE:
|
| 16 |
+
replace_with = ' volatile ' + replace_with.lstrip()
|
| 17 |
+
if quals & Q_RESTRICT:
|
| 18 |
+
# It seems that __restrict is supported by gcc and msvc.
|
| 19 |
+
# If you hit some different compiler, add a #define in
|
| 20 |
+
# _cffi_include.h for it (and in its copies, documented there)
|
| 21 |
+
replace_with = ' __restrict ' + replace_with.lstrip()
|
| 22 |
+
return replace_with
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class BaseTypeByIdentity(object):
|
| 26 |
+
is_array_type = False
|
| 27 |
+
is_raw_function = False
|
| 28 |
+
|
| 29 |
+
def get_c_name(self, replace_with='', context='a C file', quals=0):
|
| 30 |
+
result = self.c_name_with_marker
|
| 31 |
+
assert result.count('&') == 1
|
| 32 |
+
# some logic duplication with ffi.getctype()... :-(
|
| 33 |
+
replace_with = replace_with.strip()
|
| 34 |
+
if replace_with:
|
| 35 |
+
if replace_with.startswith('*') and '&[' in result:
|
| 36 |
+
replace_with = '(%s)' % replace_with
|
| 37 |
+
elif not replace_with[0] in '[(':
|
| 38 |
+
replace_with = ' ' + replace_with
|
| 39 |
+
replace_with = qualify(quals, replace_with)
|
| 40 |
+
result = result.replace('&', replace_with)
|
| 41 |
+
if '$' in result:
|
| 42 |
+
raise VerificationError(
|
| 43 |
+
"cannot generate '%s' in %s: unknown type name"
|
| 44 |
+
% (self._get_c_name(), context))
|
| 45 |
+
return result
|
| 46 |
+
|
| 47 |
+
def _get_c_name(self):
|
| 48 |
+
return self.c_name_with_marker.replace('&', '')
|
| 49 |
+
|
| 50 |
+
def has_c_name(self):
|
| 51 |
+
return '$' not in self._get_c_name()
|
| 52 |
+
|
| 53 |
+
def is_integer_type(self):
|
| 54 |
+
return False
|
| 55 |
+
|
| 56 |
+
def get_cached_btype(self, ffi, finishlist, can_delay=False):
|
| 57 |
+
try:
|
| 58 |
+
BType = ffi._cached_btypes[self]
|
| 59 |
+
except KeyError:
|
| 60 |
+
BType = self.build_backend_type(ffi, finishlist)
|
| 61 |
+
BType2 = ffi._cached_btypes.setdefault(self, BType)
|
| 62 |
+
assert BType2 is BType
|
| 63 |
+
return BType
|
| 64 |
+
|
| 65 |
+
def __repr__(self):
|
| 66 |
+
return '<%s>' % (self._get_c_name(),)
|
| 67 |
+
|
| 68 |
+
def _get_items(self):
|
| 69 |
+
return [(name, getattr(self, name)) for name in self._attrs_]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class BaseType(BaseTypeByIdentity):
|
| 73 |
+
|
| 74 |
+
def __eq__(self, other):
|
| 75 |
+
return (self.__class__ == other.__class__ and
|
| 76 |
+
self._get_items() == other._get_items())
|
| 77 |
+
|
| 78 |
+
def __ne__(self, other):
|
| 79 |
+
return not self == other
|
| 80 |
+
|
| 81 |
+
def __hash__(self):
|
| 82 |
+
return hash((self.__class__, tuple(self._get_items())))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class VoidType(BaseType):
|
| 86 |
+
_attrs_ = ()
|
| 87 |
+
|
| 88 |
+
def __init__(self):
|
| 89 |
+
self.c_name_with_marker = 'void&'
|
| 90 |
+
|
| 91 |
+
def build_backend_type(self, ffi, finishlist):
|
| 92 |
+
return global_cache(self, ffi, 'new_void_type')
|
| 93 |
+
|
| 94 |
+
void_type = VoidType()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class BasePrimitiveType(BaseType):
|
| 98 |
+
def is_complex_type(self):
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class PrimitiveType(BasePrimitiveType):
|
| 103 |
+
_attrs_ = ('name',)
|
| 104 |
+
|
| 105 |
+
ALL_PRIMITIVE_TYPES = {
|
| 106 |
+
'char': 'c',
|
| 107 |
+
'short': 'i',
|
| 108 |
+
'int': 'i',
|
| 109 |
+
'long': 'i',
|
| 110 |
+
'long long': 'i',
|
| 111 |
+
'signed char': 'i',
|
| 112 |
+
'unsigned char': 'i',
|
| 113 |
+
'unsigned short': 'i',
|
| 114 |
+
'unsigned int': 'i',
|
| 115 |
+
'unsigned long': 'i',
|
| 116 |
+
'unsigned long long': 'i',
|
| 117 |
+
'float': 'f',
|
| 118 |
+
'double': 'f',
|
| 119 |
+
'long double': 'f',
|
| 120 |
+
'_cffi_float_complex_t': 'j',
|
| 121 |
+
'_cffi_double_complex_t': 'j',
|
| 122 |
+
'_Bool': 'i',
|
| 123 |
+
# the following types are not primitive in the C sense
|
| 124 |
+
'wchar_t': 'c',
|
| 125 |
+
'char16_t': 'c',
|
| 126 |
+
'char32_t': 'c',
|
| 127 |
+
'int8_t': 'i',
|
| 128 |
+
'uint8_t': 'i',
|
| 129 |
+
'int16_t': 'i',
|
| 130 |
+
'uint16_t': 'i',
|
| 131 |
+
'int32_t': 'i',
|
| 132 |
+
'uint32_t': 'i',
|
| 133 |
+
'int64_t': 'i',
|
| 134 |
+
'uint64_t': 'i',
|
| 135 |
+
'int_least8_t': 'i',
|
| 136 |
+
'uint_least8_t': 'i',
|
| 137 |
+
'int_least16_t': 'i',
|
| 138 |
+
'uint_least16_t': 'i',
|
| 139 |
+
'int_least32_t': 'i',
|
| 140 |
+
'uint_least32_t': 'i',
|
| 141 |
+
'int_least64_t': 'i',
|
| 142 |
+
'uint_least64_t': 'i',
|
| 143 |
+
'int_fast8_t': 'i',
|
| 144 |
+
'uint_fast8_t': 'i',
|
| 145 |
+
'int_fast16_t': 'i',
|
| 146 |
+
'uint_fast16_t': 'i',
|
| 147 |
+
'int_fast32_t': 'i',
|
| 148 |
+
'uint_fast32_t': 'i',
|
| 149 |
+
'int_fast64_t': 'i',
|
| 150 |
+
'uint_fast64_t': 'i',
|
| 151 |
+
'intptr_t': 'i',
|
| 152 |
+
'uintptr_t': 'i',
|
| 153 |
+
'intmax_t': 'i',
|
| 154 |
+
'uintmax_t': 'i',
|
| 155 |
+
'ptrdiff_t': 'i',
|
| 156 |
+
'size_t': 'i',
|
| 157 |
+
'ssize_t': 'i',
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
def __init__(self, name):
|
| 161 |
+
assert name in self.ALL_PRIMITIVE_TYPES
|
| 162 |
+
self.name = name
|
| 163 |
+
self.c_name_with_marker = name + '&'
|
| 164 |
+
|
| 165 |
+
def is_char_type(self):
|
| 166 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'c'
|
| 167 |
+
def is_integer_type(self):
|
| 168 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'i'
|
| 169 |
+
def is_float_type(self):
|
| 170 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'f'
|
| 171 |
+
def is_complex_type(self):
|
| 172 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'j'
|
| 173 |
+
|
| 174 |
+
def build_backend_type(self, ffi, finishlist):
|
| 175 |
+
return global_cache(self, ffi, 'new_primitive_type', self.name)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class UnknownIntegerType(BasePrimitiveType):
|
| 179 |
+
_attrs_ = ('name',)
|
| 180 |
+
|
| 181 |
+
def __init__(self, name):
|
| 182 |
+
self.name = name
|
| 183 |
+
self.c_name_with_marker = name + '&'
|
| 184 |
+
|
| 185 |
+
def is_integer_type(self):
|
| 186 |
+
return True
|
| 187 |
+
|
| 188 |
+
def build_backend_type(self, ffi, finishlist):
|
| 189 |
+
raise NotImplementedError("integer type '%s' can only be used after "
|
| 190 |
+
"compilation" % self.name)
|
| 191 |
+
|
| 192 |
+
class UnknownFloatType(BasePrimitiveType):
|
| 193 |
+
_attrs_ = ('name', )
|
| 194 |
+
|
| 195 |
+
def __init__(self, name):
|
| 196 |
+
self.name = name
|
| 197 |
+
self.c_name_with_marker = name + '&'
|
| 198 |
+
|
| 199 |
+
def build_backend_type(self, ffi, finishlist):
|
| 200 |
+
raise NotImplementedError("float type '%s' can only be used after "
|
| 201 |
+
"compilation" % self.name)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class BaseFunctionType(BaseType):
|
| 205 |
+
_attrs_ = ('args', 'result', 'ellipsis', 'abi')
|
| 206 |
+
|
| 207 |
+
def __init__(self, args, result, ellipsis, abi=None):
|
| 208 |
+
self.args = args
|
| 209 |
+
self.result = result
|
| 210 |
+
self.ellipsis = ellipsis
|
| 211 |
+
self.abi = abi
|
| 212 |
+
#
|
| 213 |
+
reprargs = [arg._get_c_name() for arg in self.args]
|
| 214 |
+
if self.ellipsis:
|
| 215 |
+
reprargs.append('...')
|
| 216 |
+
reprargs = reprargs or ['void']
|
| 217 |
+
replace_with = self._base_pattern % (', '.join(reprargs),)
|
| 218 |
+
if abi is not None:
|
| 219 |
+
replace_with = replace_with[:1] + abi + ' ' + replace_with[1:]
|
| 220 |
+
self.c_name_with_marker = (
|
| 221 |
+
self.result.c_name_with_marker.replace('&', replace_with))
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class RawFunctionType(BaseFunctionType):
|
| 225 |
+
# Corresponds to a C type like 'int(int)', which is the C type of
|
| 226 |
+
# a function, but not a pointer-to-function. The backend has no
|
| 227 |
+
# notion of such a type; it's used temporarily by parsing.
|
| 228 |
+
_base_pattern = '(&)(%s)'
|
| 229 |
+
is_raw_function = True
|
| 230 |
+
|
| 231 |
+
def build_backend_type(self, ffi, finishlist):
|
| 232 |
+
raise CDefError("cannot render the type %r: it is a function "
|
| 233 |
+
"type, not a pointer-to-function type" % (self,))
|
| 234 |
+
|
| 235 |
+
def as_function_pointer(self):
|
| 236 |
+
return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class FunctionPtrType(BaseFunctionType):
|
| 240 |
+
_base_pattern = '(*&)(%s)'
|
| 241 |
+
|
| 242 |
+
def build_backend_type(self, ffi, finishlist):
|
| 243 |
+
result = self.result.get_cached_btype(ffi, finishlist)
|
| 244 |
+
args = []
|
| 245 |
+
for tp in self.args:
|
| 246 |
+
args.append(tp.get_cached_btype(ffi, finishlist))
|
| 247 |
+
abi_args = ()
|
| 248 |
+
if self.abi == "__stdcall":
|
| 249 |
+
if not self.ellipsis: # __stdcall ignored for variadic funcs
|
| 250 |
+
try:
|
| 251 |
+
abi_args = (ffi._backend.FFI_STDCALL,)
|
| 252 |
+
except AttributeError:
|
| 253 |
+
pass
|
| 254 |
+
return global_cache(self, ffi, 'new_function_type',
|
| 255 |
+
tuple(args), result, self.ellipsis, *abi_args)
|
| 256 |
+
|
| 257 |
+
def as_raw_function(self):
|
| 258 |
+
return RawFunctionType(self.args, self.result, self.ellipsis, self.abi)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class PointerType(BaseType):
|
| 262 |
+
_attrs_ = ('totype', 'quals')
|
| 263 |
+
|
| 264 |
+
def __init__(self, totype, quals=0):
|
| 265 |
+
self.totype = totype
|
| 266 |
+
self.quals = quals
|
| 267 |
+
extra = " *&"
|
| 268 |
+
if totype.is_array_type:
|
| 269 |
+
extra = "(%s)" % (extra.lstrip(),)
|
| 270 |
+
extra = qualify(quals, extra)
|
| 271 |
+
self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra)
|
| 272 |
+
|
| 273 |
+
def build_backend_type(self, ffi, finishlist):
|
| 274 |
+
BItem = self.totype.get_cached_btype(ffi, finishlist, can_delay=True)
|
| 275 |
+
return global_cache(self, ffi, 'new_pointer_type', BItem)
|
| 276 |
+
|
| 277 |
+
voidp_type = PointerType(void_type)
|
| 278 |
+
|
| 279 |
+
def ConstPointerType(totype):
|
| 280 |
+
return PointerType(totype, Q_CONST)
|
| 281 |
+
|
| 282 |
+
const_voidp_type = ConstPointerType(void_type)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class NamedPointerType(PointerType):
|
| 286 |
+
_attrs_ = ('totype', 'name')
|
| 287 |
+
|
| 288 |
+
def __init__(self, totype, name, quals=0):
|
| 289 |
+
PointerType.__init__(self, totype, quals)
|
| 290 |
+
self.name = name
|
| 291 |
+
self.c_name_with_marker = name + '&'
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class ArrayType(BaseType):
|
| 295 |
+
_attrs_ = ('item', 'length')
|
| 296 |
+
is_array_type = True
|
| 297 |
+
|
| 298 |
+
def __init__(self, item, length):
|
| 299 |
+
self.item = item
|
| 300 |
+
self.length = length
|
| 301 |
+
#
|
| 302 |
+
if length is None:
|
| 303 |
+
brackets = '&[]'
|
| 304 |
+
elif length == '...':
|
| 305 |
+
brackets = '&[/*...*/]'
|
| 306 |
+
else:
|
| 307 |
+
brackets = '&[%s]' % length
|
| 308 |
+
self.c_name_with_marker = (
|
| 309 |
+
self.item.c_name_with_marker.replace('&', brackets))
|
| 310 |
+
|
| 311 |
+
def length_is_unknown(self):
|
| 312 |
+
return isinstance(self.length, str)
|
| 313 |
+
|
| 314 |
+
def resolve_length(self, newlength):
|
| 315 |
+
return ArrayType(self.item, newlength)
|
| 316 |
+
|
| 317 |
+
def build_backend_type(self, ffi, finishlist):
|
| 318 |
+
if self.length_is_unknown():
|
| 319 |
+
raise CDefError("cannot render the type %r: unknown length" %
|
| 320 |
+
(self,))
|
| 321 |
+
self.item.get_cached_btype(ffi, finishlist) # force the item BType
|
| 322 |
+
BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist)
|
| 323 |
+
return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length)
|
| 324 |
+
|
| 325 |
+
char_array_type = ArrayType(PrimitiveType('char'), None)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class StructOrUnionOrEnum(BaseTypeByIdentity):
|
| 329 |
+
_attrs_ = ('name',)
|
| 330 |
+
forcename = None
|
| 331 |
+
|
| 332 |
+
def build_c_name_with_marker(self):
|
| 333 |
+
name = self.forcename or '%s %s' % (self.kind, self.name)
|
| 334 |
+
self.c_name_with_marker = name + '&'
|
| 335 |
+
|
| 336 |
+
def force_the_name(self, forcename):
|
| 337 |
+
self.forcename = forcename
|
| 338 |
+
self.build_c_name_with_marker()
|
| 339 |
+
|
| 340 |
+
def get_official_name(self):
|
| 341 |
+
assert self.c_name_with_marker.endswith('&')
|
| 342 |
+
return self.c_name_with_marker[:-1]
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
class StructOrUnion(StructOrUnionOrEnum):
|
| 346 |
+
fixedlayout = None
|
| 347 |
+
completed = 0
|
| 348 |
+
partial = False
|
| 349 |
+
packed = 0
|
| 350 |
+
|
| 351 |
+
def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None):
|
| 352 |
+
self.name = name
|
| 353 |
+
self.fldnames = fldnames
|
| 354 |
+
self.fldtypes = fldtypes
|
| 355 |
+
self.fldbitsize = fldbitsize
|
| 356 |
+
self.fldquals = fldquals
|
| 357 |
+
self.build_c_name_with_marker()
|
| 358 |
+
|
| 359 |
+
def anonymous_struct_fields(self):
|
| 360 |
+
if self.fldtypes is not None:
|
| 361 |
+
for name, type in zip(self.fldnames, self.fldtypes):
|
| 362 |
+
if name == '' and isinstance(type, StructOrUnion):
|
| 363 |
+
yield type
|
| 364 |
+
|
| 365 |
+
def enumfields(self, expand_anonymous_struct_union=True):
|
| 366 |
+
fldquals = self.fldquals
|
| 367 |
+
if fldquals is None:
|
| 368 |
+
fldquals = (0,) * len(self.fldnames)
|
| 369 |
+
for name, type, bitsize, quals in zip(self.fldnames, self.fldtypes,
|
| 370 |
+
self.fldbitsize, fldquals):
|
| 371 |
+
if (name == '' and isinstance(type, StructOrUnion)
|
| 372 |
+
and expand_anonymous_struct_union):
|
| 373 |
+
# nested anonymous struct/union
|
| 374 |
+
for result in type.enumfields():
|
| 375 |
+
yield result
|
| 376 |
+
else:
|
| 377 |
+
yield (name, type, bitsize, quals)
|
| 378 |
+
|
| 379 |
+
def force_flatten(self):
|
| 380 |
+
# force the struct or union to have a declaration that lists
|
| 381 |
+
# directly all fields returned by enumfields(), flattening
|
| 382 |
+
# nested anonymous structs/unions.
|
| 383 |
+
names = []
|
| 384 |
+
types = []
|
| 385 |
+
bitsizes = []
|
| 386 |
+
fldquals = []
|
| 387 |
+
for name, type, bitsize, quals in self.enumfields():
|
| 388 |
+
names.append(name)
|
| 389 |
+
types.append(type)
|
| 390 |
+
bitsizes.append(bitsize)
|
| 391 |
+
fldquals.append(quals)
|
| 392 |
+
self.fldnames = tuple(names)
|
| 393 |
+
self.fldtypes = tuple(types)
|
| 394 |
+
self.fldbitsize = tuple(bitsizes)
|
| 395 |
+
self.fldquals = tuple(fldquals)
|
| 396 |
+
|
| 397 |
+
def get_cached_btype(self, ffi, finishlist, can_delay=False):
|
| 398 |
+
BType = StructOrUnionOrEnum.get_cached_btype(self, ffi, finishlist,
|
| 399 |
+
can_delay)
|
| 400 |
+
if not can_delay:
|
| 401 |
+
self.finish_backend_type(ffi, finishlist)
|
| 402 |
+
return BType
|
| 403 |
+
|
| 404 |
+
def finish_backend_type(self, ffi, finishlist):
|
| 405 |
+
if self.completed:
|
| 406 |
+
if self.completed != 2:
|
| 407 |
+
raise NotImplementedError("recursive structure declaration "
|
| 408 |
+
"for '%s'" % (self.name,))
|
| 409 |
+
return
|
| 410 |
+
BType = ffi._cached_btypes[self]
|
| 411 |
+
#
|
| 412 |
+
self.completed = 1
|
| 413 |
+
#
|
| 414 |
+
if self.fldtypes is None:
|
| 415 |
+
pass # not completing it: it's an opaque struct
|
| 416 |
+
#
|
| 417 |
+
elif self.fixedlayout is None:
|
| 418 |
+
fldtypes = [tp.get_cached_btype(ffi, finishlist)
|
| 419 |
+
for tp in self.fldtypes]
|
| 420 |
+
lst = list(zip(self.fldnames, fldtypes, self.fldbitsize))
|
| 421 |
+
extra_flags = ()
|
| 422 |
+
if self.packed:
|
| 423 |
+
if self.packed == 1:
|
| 424 |
+
extra_flags = (8,) # SF_PACKED
|
| 425 |
+
else:
|
| 426 |
+
extra_flags = (0, self.packed)
|
| 427 |
+
ffi._backend.complete_struct_or_union(BType, lst, self,
|
| 428 |
+
-1, -1, *extra_flags)
|
| 429 |
+
#
|
| 430 |
+
else:
|
| 431 |
+
fldtypes = []
|
| 432 |
+
fieldofs, fieldsize, totalsize, totalalignment = self.fixedlayout
|
| 433 |
+
for i in range(len(self.fldnames)):
|
| 434 |
+
fsize = fieldsize[i]
|
| 435 |
+
ftype = self.fldtypes[i]
|
| 436 |
+
#
|
| 437 |
+
if isinstance(ftype, ArrayType) and ftype.length_is_unknown():
|
| 438 |
+
# fix the length to match the total size
|
| 439 |
+
BItemType = ftype.item.get_cached_btype(ffi, finishlist)
|
| 440 |
+
nlen, nrest = divmod(fsize, ffi.sizeof(BItemType))
|
| 441 |
+
if nrest != 0:
|
| 442 |
+
self._verification_error(
|
| 443 |
+
"field '%s.%s' has a bogus size?" % (
|
| 444 |
+
self.name, self.fldnames[i] or '{}'))
|
| 445 |
+
ftype = ftype.resolve_length(nlen)
|
| 446 |
+
self.fldtypes = (self.fldtypes[:i] + (ftype,) +
|
| 447 |
+
self.fldtypes[i+1:])
|
| 448 |
+
#
|
| 449 |
+
BFieldType = ftype.get_cached_btype(ffi, finishlist)
|
| 450 |
+
if isinstance(ftype, ArrayType) and ftype.length is None:
|
| 451 |
+
assert fsize == 0
|
| 452 |
+
else:
|
| 453 |
+
bitemsize = ffi.sizeof(BFieldType)
|
| 454 |
+
if bitemsize != fsize:
|
| 455 |
+
self._verification_error(
|
| 456 |
+
"field '%s.%s' is declared as %d bytes, but is "
|
| 457 |
+
"really %d bytes" % (self.name,
|
| 458 |
+
self.fldnames[i] or '{}',
|
| 459 |
+
bitemsize, fsize))
|
| 460 |
+
fldtypes.append(BFieldType)
|
| 461 |
+
#
|
| 462 |
+
lst = list(zip(self.fldnames, fldtypes, self.fldbitsize, fieldofs))
|
| 463 |
+
ffi._backend.complete_struct_or_union(BType, lst, self,
|
| 464 |
+
totalsize, totalalignment)
|
| 465 |
+
self.completed = 2
|
| 466 |
+
|
| 467 |
+
def _verification_error(self, msg):
|
| 468 |
+
raise VerificationError(msg)
|
| 469 |
+
|
| 470 |
+
def check_not_partial(self):
|
| 471 |
+
if self.partial and self.fixedlayout is None:
|
| 472 |
+
raise VerificationMissing(self._get_c_name())
|
| 473 |
+
|
| 474 |
+
def build_backend_type(self, ffi, finishlist):
|
| 475 |
+
self.check_not_partial()
|
| 476 |
+
finishlist.append(self)
|
| 477 |
+
#
|
| 478 |
+
return global_cache(self, ffi, 'new_%s_type' % self.kind,
|
| 479 |
+
self.get_official_name(), key=self)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class StructType(StructOrUnion):
|
| 483 |
+
kind = 'struct'
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class UnionType(StructOrUnion):
|
| 487 |
+
kind = 'union'
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class EnumType(StructOrUnionOrEnum):
|
| 491 |
+
kind = 'enum'
|
| 492 |
+
partial = False
|
| 493 |
+
partial_resolved = False
|
| 494 |
+
|
| 495 |
+
def __init__(self, name, enumerators, enumvalues, baseinttype=None):
|
| 496 |
+
self.name = name
|
| 497 |
+
self.enumerators = enumerators
|
| 498 |
+
self.enumvalues = enumvalues
|
| 499 |
+
self.baseinttype = baseinttype
|
| 500 |
+
self.build_c_name_with_marker()
|
| 501 |
+
|
| 502 |
+
def force_the_name(self, forcename):
|
| 503 |
+
StructOrUnionOrEnum.force_the_name(self, forcename)
|
| 504 |
+
if self.forcename is None:
|
| 505 |
+
name = self.get_official_name()
|
| 506 |
+
self.forcename = '$' + name.replace(' ', '_')
|
| 507 |
+
|
| 508 |
+
def check_not_partial(self):
|
| 509 |
+
if self.partial and not self.partial_resolved:
|
| 510 |
+
raise VerificationMissing(self._get_c_name())
|
| 511 |
+
|
| 512 |
+
def build_backend_type(self, ffi, finishlist):
|
| 513 |
+
self.check_not_partial()
|
| 514 |
+
base_btype = self.build_baseinttype(ffi, finishlist)
|
| 515 |
+
return global_cache(self, ffi, 'new_enum_type',
|
| 516 |
+
self.get_official_name(),
|
| 517 |
+
self.enumerators, self.enumvalues,
|
| 518 |
+
base_btype, key=self)
|
| 519 |
+
|
| 520 |
+
def build_baseinttype(self, ffi, finishlist):
|
| 521 |
+
if self.baseinttype is not None:
|
| 522 |
+
return self.baseinttype.get_cached_btype(ffi, finishlist)
|
| 523 |
+
#
|
| 524 |
+
if self.enumvalues:
|
| 525 |
+
smallest_value = min(self.enumvalues)
|
| 526 |
+
largest_value = max(self.enumvalues)
|
| 527 |
+
else:
|
| 528 |
+
import warnings
|
| 529 |
+
try:
|
| 530 |
+
# XXX! The goal is to ensure that the warnings.warn()
|
| 531 |
+
# will not suppress the warning. We want to get it
|
| 532 |
+
# several times if we reach this point several times.
|
| 533 |
+
__warningregistry__.clear()
|
| 534 |
+
except NameError:
|
| 535 |
+
pass
|
| 536 |
+
warnings.warn("%r has no values explicitly defined; "
|
| 537 |
+
"guessing that it is equivalent to 'unsigned int'"
|
| 538 |
+
% self._get_c_name())
|
| 539 |
+
smallest_value = largest_value = 0
|
| 540 |
+
if smallest_value < 0: # needs a signed type
|
| 541 |
+
sign = 1
|
| 542 |
+
candidate1 = PrimitiveType("int")
|
| 543 |
+
candidate2 = PrimitiveType("long")
|
| 544 |
+
else:
|
| 545 |
+
sign = 0
|
| 546 |
+
candidate1 = PrimitiveType("unsigned int")
|
| 547 |
+
candidate2 = PrimitiveType("unsigned long")
|
| 548 |
+
btype1 = candidate1.get_cached_btype(ffi, finishlist)
|
| 549 |
+
btype2 = candidate2.get_cached_btype(ffi, finishlist)
|
| 550 |
+
size1 = ffi.sizeof(btype1)
|
| 551 |
+
size2 = ffi.sizeof(btype2)
|
| 552 |
+
if (smallest_value >= ((-1) << (8*size1-1)) and
|
| 553 |
+
largest_value < (1 << (8*size1-sign))):
|
| 554 |
+
return btype1
|
| 555 |
+
if (smallest_value >= ((-1) << (8*size2-1)) and
|
| 556 |
+
largest_value < (1 << (8*size2-sign))):
|
| 557 |
+
return btype2
|
| 558 |
+
raise CDefError("%s values don't all fit into either 'long' "
|
| 559 |
+
"or 'unsigned long'" % self._get_c_name())
|
| 560 |
+
|
| 561 |
+
def unknown_type(name, structname=None):
|
| 562 |
+
if structname is None:
|
| 563 |
+
structname = '$%s' % name
|
| 564 |
+
tp = StructType(structname, None, None, None)
|
| 565 |
+
tp.force_the_name(name)
|
| 566 |
+
tp.origin = "unknown_type"
|
| 567 |
+
return tp
|
| 568 |
+
|
| 569 |
+
def unknown_ptr_type(name, structname=None):
|
| 570 |
+
if structname is None:
|
| 571 |
+
structname = '$$%s' % name
|
| 572 |
+
tp = StructType(structname, None, None, None)
|
| 573 |
+
return NamedPointerType(tp, name)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
global_lock = allocate_lock()
|
| 577 |
+
_typecache_cffi_backend = weakref.WeakValueDictionary()
|
| 578 |
+
|
| 579 |
+
def get_typecache(backend):
|
| 580 |
+
# returns _typecache_cffi_backend if backend is the _cffi_backend
|
| 581 |
+
# module, or type(backend).__typecache if backend is an instance of
|
| 582 |
+
# CTypesBackend (or some FakeBackend class during tests)
|
| 583 |
+
if isinstance(backend, types.ModuleType):
|
| 584 |
+
return _typecache_cffi_backend
|
| 585 |
+
with global_lock:
|
| 586 |
+
if not hasattr(type(backend), '__typecache'):
|
| 587 |
+
type(backend).__typecache = weakref.WeakValueDictionary()
|
| 588 |
+
return type(backend).__typecache
|
| 589 |
+
|
| 590 |
+
def global_cache(srctype, ffi, funcname, *args, **kwds):
|
| 591 |
+
key = kwds.pop('key', (funcname, args))
|
| 592 |
+
assert not kwds
|
| 593 |
+
try:
|
| 594 |
+
return ffi._typecache[key]
|
| 595 |
+
except KeyError:
|
| 596 |
+
pass
|
| 597 |
+
try:
|
| 598 |
+
res = getattr(ffi._backend, funcname)(*args)
|
| 599 |
+
except NotImplementedError as e:
|
| 600 |
+
raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e))
|
| 601 |
+
# note that setdefault() on WeakValueDictionary is not atomic
|
| 602 |
+
# and contains a rare bug (http://bugs.python.org/issue19542);
|
| 603 |
+
# we have to use a lock and do it ourselves
|
| 604 |
+
cache = ffi._typecache
|
| 605 |
+
with global_lock:
|
| 606 |
+
res1 = cache.get(key)
|
| 607 |
+
if res1 is None:
|
| 608 |
+
cache[key] = res
|
| 609 |
+
return res
|
| 610 |
+
else:
|
| 611 |
+
return res1
|
| 612 |
+
|
| 613 |
+
def pointer_cache(ffi, BType):
|
| 614 |
+
return global_cache('?', ffi, 'new_pointer_type', BType)
|
| 615 |
+
|
| 616 |
+
def attach_exception_info(e, name):
|
| 617 |
+
if e.args and type(e.args[0]) is str:
|
| 618 |
+
e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/parse_c_type.h
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ode, arg) (_cffi_opcode_t)(opcode | (((uintptr_t)(arg)) << 8))
|
| 8 |
+
#define _CFFI_GETOP(cffi_opcode) ((unsigned char)(uintptr_t)cffi_opcode)
|
| 9 |
+
#define _CFFI_GETARG(cffi_opcode) (((intptr_t)cffi_opcode) >> 8)
|
| 10 |
+
|
| 11 |
+
#define _CFFI_OP_PRIMITIVE 1
|
| 12 |
+
#define _CFFI_OP_POINTER 3
|
| 13 |
+
#define _CFFI_OP_ARRAY 5
|
| 14 |
+
#define _CFFI_OP_OPEN_ARRAY 7
|
| 15 |
+
#define _CFFI_OP_STRUCT_UNION 9
|
| 16 |
+
#define _CFFI_OP_ENUM 11
|
| 17 |
+
#define _CFFI_OP_FUNCTION 13
|
| 18 |
+
#define _CFFI_OP_FUNCTION_END 15
|
| 19 |
+
#define _CFFI_OP_NOOP 17
|
| 20 |
+
#define _CFFI_OP_BITFIELD 19
|
| 21 |
+
#define _CFFI_OP_TYPENAME 21
|
| 22 |
+
#define _CFFI_OP_CPYTHON_BLTN_V 23 // varargs
|
| 23 |
+
#define _CFFI_OP_CPYTHON_BLTN_N 25 // noargs
|
| 24 |
+
#define _CFFI_OP_CPYTHON_BLTN_O 27 // O (i.e. a single arg)
|
| 25 |
+
#define _CFFI_OP_CONSTANT 29
|
| 26 |
+
#define _CFFI_OP_CONSTANT_INT 31
|
| 27 |
+
#define _CFFI_OP_GLOBAL_VAR 33
|
| 28 |
+
#define _CFFI_OP_DLOPEN_FUNC 35
|
| 29 |
+
#define _CFFI_OP_DLOPEN_CONST 37
|
| 30 |
+
#define _CFFI_OP_GLOBAL_VAR_F 39
|
| 31 |
+
#define _CFFI_OP_EXTERN_PYTHON 41
|
| 32 |
+
|
| 33 |
+
#define _CFFI_PRIM_VOID 0
|
| 34 |
+
#define _CFFI_PRIM_BOOL 1
|
| 35 |
+
#define _CFFI_PRIM_CHAR 2
|
| 36 |
+
#define _CFFI_PRIM_SCHAR 3
|
| 37 |
+
#define _CFFI_PRIM_UCHAR 4
|
| 38 |
+
#define _CFFI_PRIM_SHORT 5
|
| 39 |
+
#define _CFFI_PRIM_USHORT 6
|
| 40 |
+
#define _CFFI_PRIM_INT 7
|
| 41 |
+
#define _CFFI_PRIM_UINT 8
|
| 42 |
+
#define _CFFI_PRIM_LONG 9
|
| 43 |
+
#define _CFFI_PRIM_ULONG 10
|
| 44 |
+
#define _CFFI_PRIM_LONGLONG 11
|
| 45 |
+
#define _CFFI_PRIM_ULONGLONG 12
|
| 46 |
+
#define _CFFI_PRIM_FLOAT 13
|
| 47 |
+
#define _CFFI_PRIM_DOUBLE 14
|
| 48 |
+
#define _CFFI_PRIM_LONGDOUBLE 15
|
| 49 |
+
|
| 50 |
+
#define _CFFI_PRIM_WCHAR 16
|
| 51 |
+
#define _CFFI_PRIM_INT8 17
|
| 52 |
+
#define _CFFI_PRIM_UINT8 18
|
| 53 |
+
#define _CFFI_PRIM_INT16 19
|
| 54 |
+
#define _CFFI_PRIM_UINT16 20
|
| 55 |
+
#define _CFFI_PRIM_INT32 21
|
| 56 |
+
#define _CFFI_PRIM_UINT32 22
|
| 57 |
+
#define _CFFI_PRIM_INT64 23
|
| 58 |
+
#define _CFFI_PRIM_UINT64 24
|
| 59 |
+
#define _CFFI_PRIM_INTPTR 25
|
| 60 |
+
#define _CFFI_PRIM_UINTPTR 26
|
| 61 |
+
#define _CFFI_PRIM_PTRDIFF 27
|
| 62 |
+
#define _CFFI_PRIM_SIZE 28
|
| 63 |
+
#define _CFFI_PRIM_SSIZE 29
|
| 64 |
+
#define _CFFI_PRIM_INT_LEAST8 30
|
| 65 |
+
#define _CFFI_PRIM_UINT_LEAST8 31
|
| 66 |
+
#define _CFFI_PRIM_INT_LEAST16 32
|
| 67 |
+
#define _CFFI_PRIM_UINT_LEAST16 33
|
| 68 |
+
#define _CFFI_PRIM_INT_LEAST32 34
|
| 69 |
+
#define _CFFI_PRIM_UINT_LEAST32 35
|
| 70 |
+
#define _CFFI_PRIM_INT_LEAST64 36
|
| 71 |
+
#define _CFFI_PRIM_UINT_LEAST64 37
|
| 72 |
+
#define _CFFI_PRIM_INT_FAST8 38
|
| 73 |
+
#define _CFFI_PRIM_UINT_FAST8 39
|
| 74 |
+
#define _CFFI_PRIM_INT_FAST16 40
|
| 75 |
+
#define _CFFI_PRIM_UINT_FAST16 41
|
| 76 |
+
#define _CFFI_PRIM_INT_FAST32 42
|
| 77 |
+
#define _CFFI_PRIM_UINT_FAST32 43
|
| 78 |
+
#define _CFFI_PRIM_INT_FAST64 44
|
| 79 |
+
#define _CFFI_PRIM_UINT_FAST64 45
|
| 80 |
+
#define _CFFI_PRIM_INTMAX 46
|
| 81 |
+
#define _CFFI_PRIM_UINTMAX 47
|
| 82 |
+
#define _CFFI_PRIM_FLOATCOMPLEX 48
|
| 83 |
+
#define _CFFI_PRIM_DOUBLECOMPLEX 49
|
| 84 |
+
#define _CFFI_PRIM_CHAR16 50
|
| 85 |
+
#define _CFFI_PRIM_CHAR32 51
|
| 86 |
+
|
| 87 |
+
#define _CFFI__NUM_PRIM 52
|
| 88 |
+
#define _CFFI__UNKNOWN_PRIM (-1)
|
| 89 |
+
#define _CFFI__UNKNOWN_FLOAT_PRIM (-2)
|
| 90 |
+
#define _CFFI__UNKNOWN_LONG_DOUBLE (-3)
|
| 91 |
+
|
| 92 |
+
#define _CFFI__IO_FILE_STRUCT (-1)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
struct _cffi_global_s {
|
| 96 |
+
const char *name;
|
| 97 |
+
void *address;
|
| 98 |
+
_cffi_opcode_t type_op;
|
| 99 |
+
void *size_or_direct_fn; // OP_GLOBAL_VAR: size, or 0 if unknown
|
| 100 |
+
// OP_CPYTHON_BLTN_*: addr of direct function
|
| 101 |
+
};
|
| 102 |
+
|
| 103 |
+
struct _cffi_getconst_s {
|
| 104 |
+
unsigned long long value;
|
| 105 |
+
const struct _cffi_type_context_s *ctx;
|
| 106 |
+
int gindex;
|
| 107 |
+
};
|
| 108 |
+
|
| 109 |
+
struct _cffi_struct_union_s {
|
| 110 |
+
const char *name;
|
| 111 |
+
int type_index; // -> _cffi_types, on a OP_STRUCT_UNION
|
| 112 |
+
int flags; // _CFFI_F_* flags below
|
| 113 |
+
size_t size;
|
| 114 |
+
int alignment;
|
| 115 |
+
int first_field_index; // -> _cffi_fields array
|
| 116 |
+
int num_fields;
|
| 117 |
+
};
|
| 118 |
+
#define _CFFI_F_UNION 0x01 // is a union, not a struct
|
| 119 |
+
#define _CFFI_F_CHECK_FIELDS 0x02 // complain if fields are not in the
|
| 120 |
+
// "standard layout" or if some are missing
|
| 121 |
+
#define _CFFI_F_PACKED 0x04 // for CHECK_FIELDS, assume a packed struct
|
| 122 |
+
#define _CFFI_F_EXTERNAL 0x08 // in some other ffi.include()
|
| 123 |
+
#define _CFFI_F_OPAQUE 0x10 // opaque
|
| 124 |
+
|
| 125 |
+
struct _cffi_field_s {
|
| 126 |
+
const char *name;
|
| 127 |
+
size_t field_offset;
|
| 128 |
+
size_t field_size;
|
| 129 |
+
_cffi_opcode_t field_type_op;
|
| 130 |
+
};
|
| 131 |
+
|
| 132 |
+
struct _cffi_enum_s {
|
| 133 |
+
const char *name;
|
| 134 |
+
int type_index; // -> _cffi_types, on a OP_ENUM
|
| 135 |
+
int type_prim; // _CFFI_PRIM_xxx
|
| 136 |
+
const char *enumerators; // comma-delimited string
|
| 137 |
+
};
|
| 138 |
+
|
| 139 |
+
struct _cffi_typename_s {
|
| 140 |
+
const char *name;
|
| 141 |
+
int type_index; /* if opaque, points to a possibly artificial
|
| 142 |
+
OP_STRUCT which is itself opaque */
|
| 143 |
+
};
|
| 144 |
+
|
| 145 |
+
struct _cffi_type_context_s {
|
| 146 |
+
_cffi_opcode_t *types;
|
| 147 |
+
const struct _cffi_global_s *globals;
|
| 148 |
+
const struct _cffi_field_s *fields;
|
| 149 |
+
const struct _cffi_struct_union_s *struct_unions;
|
| 150 |
+
const struct _cffi_enum_s *enums;
|
| 151 |
+
const struct _cffi_typename_s *typenames;
|
| 152 |
+
int num_globals;
|
| 153 |
+
int num_struct_unions;
|
| 154 |
+
int num_enums;
|
| 155 |
+
int num_typenames;
|
| 156 |
+
const char *const *includes;
|
| 157 |
+
int num_types;
|
| 158 |
+
int flags; /* future extension */
|
| 159 |
+
};
|
| 160 |
+
|
| 161 |
+
struct _cffi_parse_info_s {
|
| 162 |
+
const struct _cffi_type_context_s *ctx;
|
| 163 |
+
_cffi_opcode_t *output;
|
| 164 |
+
unsigned int output_size;
|
| 165 |
+
size_t error_location;
|
| 166 |
+
const char *error_message;
|
| 167 |
+
};
|
| 168 |
+
|
| 169 |
+
struct _cffi_externpy_s {
|
| 170 |
+
const char *name;
|
| 171 |
+
size_t size_of_result;
|
| 172 |
+
void *reserved1, *reserved2;
|
| 173 |
+
};
|
| 174 |
+
|
| 175 |
+
#ifdef _CFFI_INTERNAL
|
| 176 |
+
static int parse_c_type(struct _cffi_parse_info_s *info, const char *input);
|
| 177 |
+
static int search_in_globals(const struct _cffi_type_context_s *ctx,
|
| 178 |
+
const char *search, size_t search_len);
|
| 179 |
+
static int search_in_struct_unions(const struct _cffi_type_context_s *ctx,
|
| 180 |
+
const char *search, size_t search_len);
|
| 181 |
+
#endif
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/pkgconfig.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi
|
| 2 |
+
import sys, os, subprocess
|
| 3 |
+
|
| 4 |
+
from .error import PkgConfigError
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def merge_flags(cfg1, cfg2):
|
| 8 |
+
"""Merge values from cffi config flags cfg2 to cf1
|
| 9 |
+
|
| 10 |
+
Example:
|
| 11 |
+
merge_flags({"libraries": ["one"]}, {"libraries": ["two"]})
|
| 12 |
+
{"libraries": ["one", "two"]}
|
| 13 |
+
"""
|
| 14 |
+
for key, value in cfg2.items():
|
| 15 |
+
if key not in cfg1:
|
| 16 |
+
cfg1[key] = value
|
| 17 |
+
else:
|
| 18 |
+
if not isinstance(cfg1[key], list):
|
| 19 |
+
raise TypeError("cfg1[%r] should be a list of strings" % (key,))
|
| 20 |
+
if not isinstance(value, list):
|
| 21 |
+
raise TypeError("cfg2[%r] should be a list of strings" % (key,))
|
| 22 |
+
cfg1[key].extend(value)
|
| 23 |
+
return cfg1
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def call(libname, flag, encoding=sys.getfilesystemencoding()):
|
| 27 |
+
"""Calls pkg-config and returns the output if found
|
| 28 |
+
"""
|
| 29 |
+
a = ["pkg-config", "--print-errors"]
|
| 30 |
+
a.append(flag)
|
| 31 |
+
a.append(libname)
|
| 32 |
+
try:
|
| 33 |
+
pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 34 |
+
except EnvironmentError as e:
|
| 35 |
+
raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),))
|
| 36 |
+
|
| 37 |
+
bout, berr = pc.communicate()
|
| 38 |
+
if pc.returncode != 0:
|
| 39 |
+
try:
|
| 40 |
+
berr = berr.decode(encoding)
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
raise PkgConfigError(berr.strip())
|
| 44 |
+
|
| 45 |
+
if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x
|
| 46 |
+
try:
|
| 47 |
+
bout = bout.decode(encoding)
|
| 48 |
+
except UnicodeDecodeError:
|
| 49 |
+
raise PkgConfigError("pkg-config %s %s returned bytes that cannot "
|
| 50 |
+
"be decoded with encoding %r:\n%r" %
|
| 51 |
+
(flag, libname, encoding, bout))
|
| 52 |
+
|
| 53 |
+
if os.altsep != '\\' and '\\' in bout:
|
| 54 |
+
raise PkgConfigError("pkg-config %s %s returned an unsupported "
|
| 55 |
+
"backslash-escaped output:\n%r" %
|
| 56 |
+
(flag, libname, bout))
|
| 57 |
+
return bout
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def flags_from_pkgconfig(libs):
|
| 61 |
+
r"""Return compiler line flags for FFI.set_source based on pkg-config output
|
| 62 |
+
|
| 63 |
+
Usage
|
| 64 |
+
...
|
| 65 |
+
ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"])
|
| 66 |
+
|
| 67 |
+
If pkg-config is installed on build machine, then arguments include_dirs,
|
| 68 |
+
library_dirs, libraries, define_macros, extra_compile_args and
|
| 69 |
+
extra_link_args are extended with an output of pkg-config for libfoo and
|
| 70 |
+
libbar.
|
| 71 |
+
|
| 72 |
+
Raises PkgConfigError in case the pkg-config call fails.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def get_include_dirs(string):
|
| 76 |
+
return [x[2:] for x in string.split() if x.startswith("-I")]
|
| 77 |
+
|
| 78 |
+
def get_library_dirs(string):
|
| 79 |
+
return [x[2:] for x in string.split() if x.startswith("-L")]
|
| 80 |
+
|
| 81 |
+
def get_libraries(string):
|
| 82 |
+
return [x[2:] for x in string.split() if x.startswith("-l")]
|
| 83 |
+
|
| 84 |
+
# convert -Dfoo=bar to list of tuples [("foo", "bar")] expected by distutils
|
| 85 |
+
def get_macros(string):
|
| 86 |
+
def _macro(x):
|
| 87 |
+
x = x[2:] # drop "-D"
|
| 88 |
+
if '=' in x:
|
| 89 |
+
return tuple(x.split("=", 1)) # "-Dfoo=bar" => ("foo", "bar")
|
| 90 |
+
else:
|
| 91 |
+
return (x, None) # "-Dfoo" => ("foo", None)
|
| 92 |
+
return [_macro(x) for x in string.split() if x.startswith("-D")]
|
| 93 |
+
|
| 94 |
+
def get_other_cflags(string):
|
| 95 |
+
return [x for x in string.split() if not x.startswith("-I") and
|
| 96 |
+
not x.startswith("-D")]
|
| 97 |
+
|
| 98 |
+
def get_other_libs(string):
|
| 99 |
+
return [x for x in string.split() if not x.startswith("-L") and
|
| 100 |
+
not x.startswith("-l")]
|
| 101 |
+
|
| 102 |
+
# return kwargs for given libname
|
| 103 |
+
def kwargs(libname):
|
| 104 |
+
fse = sys.getfilesystemencoding()
|
| 105 |
+
all_cflags = call(libname, "--cflags")
|
| 106 |
+
all_libs = call(libname, "--libs")
|
| 107 |
+
return {
|
| 108 |
+
"include_dirs": get_include_dirs(all_cflags),
|
| 109 |
+
"library_dirs": get_library_dirs(all_libs),
|
| 110 |
+
"libraries": get_libraries(all_libs),
|
| 111 |
+
"define_macros": get_macros(all_cflags),
|
| 112 |
+
"extra_compile_args": get_other_cflags(all_cflags),
|
| 113 |
+
"extra_link_args": get_other_libs(all_libs),
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# merge all arguments together
|
| 117 |
+
ret = {}
|
| 118 |
+
for libname in libs:
|
| 119 |
+
lib_flags = kwargs(libname)
|
| 120 |
+
merge_flags(ret, lib_flags)
|
| 121 |
+
return ret
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/cffi/recompiler.py
ADDED
|
@@ -0,0 +1,1598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io, os, sys, sysconfig
|
| 2 |
+
from . import ffiplatform, model
|
| 3 |
+
from .error import VerificationError
|
| 4 |
+
from .cffi_opcode import *
|
| 5 |
+
|
| 6 |
+
VERSION_BASE = 0x2601
|
| 7 |
+
VERSION_EMBEDDED = 0x2701
|
| 8 |
+
VERSION_CHAR16CHAR32 = 0x2801
|
| 9 |
+
|
| 10 |
+
USE_LIMITED_API = ((sys.platform != 'win32' or sys.version_info < (3, 0) or
|
| 11 |
+
sys.version_info >= (3, 5)) and
|
| 12 |
+
not sysconfig.get_config_var("Py_GIL_DISABLED")) # free-threaded doesn't yet support limited API
|
| 13 |
+
|
| 14 |
+
class GlobalExpr:
|
| 15 |
+
def __init__(self, name, address, type_op, size=0, check_value=0):
|
| 16 |
+
self.name = name
|
| 17 |
+
self.address = address
|
| 18 |
+
self.type_op = type_op
|
| 19 |
+
self.size = size
|
| 20 |
+
self.check_value = check_value
|
| 21 |
+
|
| 22 |
+
def as_c_expr(self):
|
| 23 |
+
return ' { "%s", (void *)%s, %s, (void *)%s },' % (
|
| 24 |
+
self.name, self.address, self.type_op.as_c_expr(), self.size)
|
| 25 |
+
|
| 26 |
+
def as_python_expr(self):
|
| 27 |
+
return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name,
|
| 28 |
+
self.check_value)
|
| 29 |
+
|
| 30 |
+
class FieldExpr:
|
| 31 |
+
def __init__(self, name, field_offset, field_size, fbitsize, field_type_op):
|
| 32 |
+
self.name = name
|
| 33 |
+
self.field_offset = field_offset
|
| 34 |
+
self.field_size = field_size
|
| 35 |
+
self.fbitsize = fbitsize
|
| 36 |
+
self.field_type_op = field_type_op
|
| 37 |
+
|
| 38 |
+
def as_c_expr(self):
|
| 39 |
+
spaces = " " * len(self.name)
|
| 40 |
+
return (' { "%s", %s,\n' % (self.name, self.field_offset) +
|
| 41 |
+
' %s %s,\n' % (spaces, self.field_size) +
|
| 42 |
+
' %s %s },' % (spaces, self.field_type_op.as_c_expr()))
|
| 43 |
+
|
| 44 |
+
def as_python_expr(self):
|
| 45 |
+
raise NotImplementedError
|
| 46 |
+
|
| 47 |
+
def as_field_python_expr(self):
|
| 48 |
+
if self.field_type_op.op == OP_NOOP:
|
| 49 |
+
size_expr = ''
|
| 50 |
+
elif self.field_type_op.op == OP_BITFIELD:
|
| 51 |
+
size_expr = format_four_bytes(self.fbitsize)
|
| 52 |
+
else:
|
| 53 |
+
raise NotImplementedError
|
| 54 |
+
return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(),
|
| 55 |
+
size_expr,
|
| 56 |
+
self.name)
|
| 57 |
+
|
| 58 |
+
class StructUnionExpr:
|
| 59 |
+
def __init__(self, name, type_index, flags, size, alignment, comment,
|
| 60 |
+
first_field_index, c_fields):
|
| 61 |
+
self.name = name
|
| 62 |
+
self.type_index = type_index
|
| 63 |
+
self.flags = flags
|
| 64 |
+
self.size = size
|
| 65 |
+
self.alignment = alignment
|
| 66 |
+
self.comment = comment
|
| 67 |
+
self.first_field_index = first_field_index
|
| 68 |
+
self.c_fields = c_fields
|
| 69 |
+
|
| 70 |
+
def as_c_expr(self):
|
| 71 |
+
return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags)
|
| 72 |
+
+ '\n %s, %s, ' % (self.size, self.alignment)
|
| 73 |
+
+ '%d, %d ' % (self.first_field_index, len(self.c_fields))
|
| 74 |
+
+ ('/* %s */ ' % self.comment if self.comment else '')
|
| 75 |
+
+ '},')
|
| 76 |
+
|
| 77 |
+
def as_python_expr(self):
|
| 78 |
+
flags = eval(self.flags, G_FLAGS)
|
| 79 |
+
fields_expr = [c_field.as_field_python_expr()
|
| 80 |
+
for c_field in self.c_fields]
|
| 81 |
+
return "(b'%s%s%s',%s)" % (
|
| 82 |
+
format_four_bytes(self.type_index),
|
| 83 |
+
format_four_bytes(flags),
|
| 84 |
+
self.name,
|
| 85 |
+
','.join(fields_expr))
|
| 86 |
+
|
| 87 |
+
class EnumExpr:
|
| 88 |
+
def __init__(self, name, type_index, size, signed, allenums):
|
| 89 |
+
self.name = name
|
| 90 |
+
self.type_index = type_index
|
| 91 |
+
self.size = size
|
| 92 |
+
self.signed = signed
|
| 93 |
+
self.allenums = allenums
|
| 94 |
+
|
| 95 |
+
def as_c_expr(self):
|
| 96 |
+
return (' { "%s", %d, _cffi_prim_int(%s, %s),\n'
|
| 97 |
+
' "%s" },' % (self.name, self.type_index,
|
| 98 |
+
self.size, self.signed, self.allenums))
|
| 99 |
+
|
| 100 |
+
def as_python_expr(self):
|
| 101 |
+
prim_index = {
|
| 102 |
+
(1, 0): PRIM_UINT8, (1, 1): PRIM_INT8,
|
| 103 |
+
(2, 0): PRIM_UINT16, (2, 1): PRIM_INT16,
|
| 104 |
+
(4, 0): PRIM_UINT32, (4, 1): PRIM_INT32,
|
| 105 |
+
(8, 0): PRIM_UINT64, (8, 1): PRIM_INT64,
|
| 106 |
+
}[self.size, self.signed]
|
| 107 |
+
return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index),
|
| 108 |
+
format_four_bytes(prim_index),
|
| 109 |
+
self.name, self.allenums)
|
| 110 |
+
|
| 111 |
+
class TypenameExpr:
|
| 112 |
+
def __init__(self, name, type_index):
|
| 113 |
+
self.name = name
|
| 114 |
+
self.type_index = type_index
|
| 115 |
+
|
| 116 |
+
def as_c_expr(self):
|
| 117 |
+
return ' { "%s", %d },' % (self.name, self.type_index)
|
| 118 |
+
|
| 119 |
+
def as_python_expr(self):
|
| 120 |
+
return "b'%s%s'" % (format_four_bytes(self.type_index), self.name)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ____________________________________________________________
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Recompiler:
|
| 127 |
+
_num_externpy = 0
|
| 128 |
+
|
| 129 |
+
def __init__(self, ffi, module_name, target_is_python=False):
|
| 130 |
+
self.ffi = ffi
|
| 131 |
+
self.module_name = module_name
|
| 132 |
+
self.target_is_python = target_is_python
|
| 133 |
+
self._version = VERSION_BASE
|
| 134 |
+
|
| 135 |
+
def needs_version(self, ver):
|
| 136 |
+
self._version = max(self._version, ver)
|
| 137 |
+
|
| 138 |
+
def collect_type_table(self):
|
| 139 |
+
self._typesdict = {}
|
| 140 |
+
self._generate("collecttype")
|
| 141 |
+
#
|
| 142 |
+
all_decls = sorted(self._typesdict, key=str)
|
| 143 |
+
#
|
| 144 |
+
# prepare all FUNCTION bytecode sequences first
|
| 145 |
+
self.cffi_types = []
|
| 146 |
+
for tp in all_decls:
|
| 147 |
+
if tp.is_raw_function:
|
| 148 |
+
assert self._typesdict[tp] is None
|
| 149 |
+
self._typesdict[tp] = len(self.cffi_types)
|
| 150 |
+
self.cffi_types.append(tp) # placeholder
|
| 151 |
+
for tp1 in tp.args:
|
| 152 |
+
assert isinstance(tp1, (model.VoidType,
|
| 153 |
+
model.BasePrimitiveType,
|
| 154 |
+
model.PointerType,
|
| 155 |
+
model.StructOrUnionOrEnum,
|
| 156 |
+
model.FunctionPtrType))
|
| 157 |
+
if self._typesdict[tp1] is None:
|
| 158 |
+
self._typesdict[tp1] = len(self.cffi_types)
|
| 159 |
+
self.cffi_types.append(tp1) # placeholder
|
| 160 |
+
self.cffi_types.append('END') # placeholder
|
| 161 |
+
#
|
| 162 |
+
# prepare all OTHER bytecode sequences
|
| 163 |
+
for tp in all_decls:
|
| 164 |
+
if not tp.is_raw_function and self._typesdict[tp] is None:
|
| 165 |
+
self._typesdict[tp] = len(self.cffi_types)
|
| 166 |
+
self.cffi_types.append(tp) # placeholder
|
| 167 |
+
if tp.is_array_type and tp.length is not None:
|
| 168 |
+
self.cffi_types.append('LEN') # placeholder
|
| 169 |
+
assert None not in self._typesdict.values()
|
| 170 |
+
#
|
| 171 |
+
# collect all structs and unions and enums
|
| 172 |
+
self._struct_unions = {}
|
| 173 |
+
self._enums = {}
|
| 174 |
+
for tp in all_decls:
|
| 175 |
+
if isinstance(tp, model.StructOrUnion):
|
| 176 |
+
self._struct_unions[tp] = None
|
| 177 |
+
elif isinstance(tp, model.EnumType):
|
| 178 |
+
self._enums[tp] = None
|
| 179 |
+
for i, tp in enumerate(sorted(self._struct_unions,
|
| 180 |
+
key=lambda tp: tp.name)):
|
| 181 |
+
self._struct_unions[tp] = i
|
| 182 |
+
for i, tp in enumerate(sorted(self._enums,
|
| 183 |
+
key=lambda tp: tp.name)):
|
| 184 |
+
self._enums[tp] = i
|
| 185 |
+
#
|
| 186 |
+
# emit all bytecode sequences now
|
| 187 |
+
for tp in all_decls:
|
| 188 |
+
method = getattr(self, '_emit_bytecode_' + tp.__class__.__name__)
|
| 189 |
+
method(tp, self._typesdict[tp])
|
| 190 |
+
#
|
| 191 |
+
# consistency check
|
| 192 |
+
for op in self.cffi_types:
|
| 193 |
+
assert isinstance(op, CffiOp)
|
| 194 |
+
self.cffi_types = tuple(self.cffi_types) # don't change any more
|
| 195 |
+
|
| 196 |
+
def _enum_fields(self, tp):
|
| 197 |
+
# When producing C, expand all anonymous struct/union fields.
|
| 198 |
+
# That's necessary to have C code checking the offsets of the
|
| 199 |
+
# individual fields contained in them. When producing Python,
|
| 200 |
+
# don't do it and instead write it like it is, with the
|
| 201 |
+
# corresponding fields having an empty name. Empty names are
|
| 202 |
+
# recognized at runtime when we import the generated Python
|
| 203 |
+
# file.
|
| 204 |
+
expand_anonymous_struct_union = not self.target_is_python
|
| 205 |
+
return tp.enumfields(expand_anonymous_struct_union)
|
| 206 |
+
|
| 207 |
+
def _do_collect_type(self, tp):
|
| 208 |
+
if not isinstance(tp, model.BaseTypeByIdentity):
|
| 209 |
+
if isinstance(tp, tuple):
|
| 210 |
+
for x in tp:
|
| 211 |
+
self._do_collect_type(x)
|
| 212 |
+
return
|
| 213 |
+
if tp not in self._typesdict:
|
| 214 |
+
self._typesdict[tp] = None
|
| 215 |
+
if isinstance(tp, model.FunctionPtrType):
|
| 216 |
+
self._do_collect_type(tp.as_raw_function())
|
| 217 |
+
elif isinstance(tp, model.StructOrUnion):
|
| 218 |
+
if tp.fldtypes is not None and (
|
| 219 |
+
tp not in self.ffi._parser._included_declarations):
|
| 220 |
+
for name1, tp1, _, _ in self._enum_fields(tp):
|
| 221 |
+
self._do_collect_type(self._field_type(tp, name1, tp1))
|
| 222 |
+
else:
|
| 223 |
+
for _, x in tp._get_items():
|
| 224 |
+
self._do_collect_type(x)
|
| 225 |
+
|
| 226 |
+
def _generate(self, step_name):
|
| 227 |
+
lst = self.ffi._parser._declarations.items()
|
| 228 |
+
for name, (tp, quals) in sorted(lst):
|
| 229 |
+
kind, realname = name.split(' ', 1)
|
| 230 |
+
try:
|
| 231 |
+
method = getattr(self, '_generate_cpy_%s_%s' % (kind,
|
| 232 |
+
step_name))
|
| 233 |
+
except AttributeError:
|
| 234 |
+
raise VerificationError(
|
| 235 |
+
"not implemented in recompile(): %r" % name)
|
| 236 |
+
try:
|
| 237 |
+
self._current_quals = quals
|
| 238 |
+
method(tp, realname)
|
| 239 |
+
except Exception as e:
|
| 240 |
+
model.attach_exception_info(e, name)
|
| 241 |
+
raise
|
| 242 |
+
|
| 243 |
+
# ----------
|
| 244 |
+
|
| 245 |
+
ALL_STEPS = ["global", "field", "struct_union", "enum", "typename"]
|
| 246 |
+
|
| 247 |
+
def collect_step_tables(self):
|
| 248 |
+
# collect the declarations for '_cffi_globals', '_cffi_typenames', etc.
|
| 249 |
+
self._lsts = {}
|
| 250 |
+
for step_name in self.ALL_STEPS:
|
| 251 |
+
self._lsts[step_name] = []
|
| 252 |
+
self._seen_struct_unions = set()
|
| 253 |
+
self._generate("ctx")
|
| 254 |
+
self._add_missing_struct_unions()
|
| 255 |
+
#
|
| 256 |
+
for step_name in self.ALL_STEPS:
|
| 257 |
+
lst = self._lsts[step_name]
|
| 258 |
+
if step_name != "field":
|
| 259 |
+
lst.sort(key=lambda entry: entry.name)
|
| 260 |
+
self._lsts[step_name] = tuple(lst) # don't change any more
|
| 261 |
+
#
|
| 262 |
+
# check for a possible internal inconsistency: _cffi_struct_unions
|
| 263 |
+
# should have been generated with exactly self._struct_unions
|
| 264 |
+
lst = self._lsts["struct_union"]
|
| 265 |
+
for tp, i in self._struct_unions.items():
|
| 266 |
+
assert i < len(lst)
|
| 267 |
+
assert lst[i].name == tp.name
|
| 268 |
+
assert len(lst) == len(self._struct_unions)
|
| 269 |
+
# same with enums
|
| 270 |
+
lst = self._lsts["enum"]
|
| 271 |
+
for tp, i in self._enums.items():
|
| 272 |
+
assert i < len(lst)
|
| 273 |
+
assert lst[i].name == tp.name
|
| 274 |
+
assert len(lst) == len(self._enums)
|
| 275 |
+
|
| 276 |
+
# ----------
|
| 277 |
+
|
| 278 |
+
def _prnt(self, what=''):
|
| 279 |
+
self._f.write(what + '\n')
|
| 280 |
+
|
| 281 |
+
def write_source_to_f(self, f, preamble):
|
| 282 |
+
if self.target_is_python:
|
| 283 |
+
assert preamble is None
|
| 284 |
+
self.write_py_source_to_f(f)
|
| 285 |
+
else:
|
| 286 |
+
assert preamble is not None
|
| 287 |
+
self.write_c_source_to_f(f, preamble)
|
| 288 |
+
|
| 289 |
+
def _rel_readlines(self, filename):
|
| 290 |
+
g = open(os.path.join(os.path.dirname(__file__), filename), 'r')
|
| 291 |
+
lines = g.readlines()
|
| 292 |
+
g.close()
|
| 293 |
+
return lines
|
| 294 |
+
|
| 295 |
+
def write_c_source_to_f(self, f, preamble):
|
| 296 |
+
self._f = f
|
| 297 |
+
prnt = self._prnt
|
| 298 |
+
if self.ffi._embedding is not None:
|
| 299 |
+
prnt('#define _CFFI_USE_EMBEDDING')
|
| 300 |
+
if not USE_LIMITED_API:
|
| 301 |
+
prnt('#define _CFFI_NO_LIMITED_API')
|
| 302 |
+
#
|
| 303 |
+
# first the '#include' (actually done by inlining the file's content)
|
| 304 |
+
lines = self._rel_readlines('_cffi_include.h')
|
| 305 |
+
i = lines.index('#include "parse_c_type.h"\n')
|
| 306 |
+
lines[i:i+1] = self._rel_readlines('parse_c_type.h')
|
| 307 |
+
prnt(''.join(lines))
|
| 308 |
+
#
|
| 309 |
+
# if we have ffi._embedding != None, we give it here as a macro
|
| 310 |
+
# and include an extra file
|
| 311 |
+
base_module_name = self.module_name.split('.')[-1]
|
| 312 |
+
if self.ffi._embedding is not None:
|
| 313 |
+
prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,))
|
| 314 |
+
prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {')
|
| 315 |
+
self._print_string_literal_in_array(self.ffi._embedding)
|
| 316 |
+
prnt('0 };')
|
| 317 |
+
prnt('#ifdef PYPY_VERSION')
|
| 318 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % (
|
| 319 |
+
base_module_name,))
|
| 320 |
+
prnt('#elif PY_MAJOR_VERSION >= 3')
|
| 321 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % (
|
| 322 |
+
base_module_name,))
|
| 323 |
+
prnt('#else')
|
| 324 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC init%s' % (
|
| 325 |
+
base_module_name,))
|
| 326 |
+
prnt('#endif')
|
| 327 |
+
lines = self._rel_readlines('_embedding.h')
|
| 328 |
+
i = lines.index('#include "_cffi_errors.h"\n')
|
| 329 |
+
lines[i:i+1] = self._rel_readlines('_cffi_errors.h')
|
| 330 |
+
prnt(''.join(lines))
|
| 331 |
+
self.needs_version(VERSION_EMBEDDED)
|
| 332 |
+
#
|
| 333 |
+
# then paste the C source given by the user, verbatim.
|
| 334 |
+
prnt('/************************************************************/')
|
| 335 |
+
prnt()
|
| 336 |
+
prnt(preamble)
|
| 337 |
+
prnt()
|
| 338 |
+
prnt('/************************************************************/')
|
| 339 |
+
prnt()
|
| 340 |
+
#
|
| 341 |
+
# the declaration of '_cffi_types'
|
| 342 |
+
prnt('static void *_cffi_types[] = {')
|
| 343 |
+
typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
|
| 344 |
+
for i, op in enumerate(self.cffi_types):
|
| 345 |
+
comment = ''
|
| 346 |
+
if i in typeindex2type:
|
| 347 |
+
comment = ' // ' + typeindex2type[i]._get_c_name()
|
| 348 |
+
prnt('/* %2d */ %s,%s' % (i, op.as_c_expr(), comment))
|
| 349 |
+
if not self.cffi_types:
|
| 350 |
+
prnt(' 0')
|
| 351 |
+
prnt('};')
|
| 352 |
+
prnt()
|
| 353 |
+
#
|
| 354 |
+
# call generate_cpy_xxx_decl(), for every xxx found from
|
| 355 |
+
# ffi._parser._declarations. This generates all the functions.
|
| 356 |
+
self._seen_constants = set()
|
| 357 |
+
self._generate("decl")
|
| 358 |
+
#
|
| 359 |
+
# the declaration of '_cffi_globals' and '_cffi_typenames'
|
| 360 |
+
nums = {}
|
| 361 |
+
for step_name in self.ALL_STEPS:
|
| 362 |
+
lst = self._lsts[step_name]
|
| 363 |
+
nums[step_name] = len(lst)
|
| 364 |
+
if nums[step_name] > 0:
|
| 365 |
+
prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % (
|
| 366 |
+
step_name, step_name))
|
| 367 |
+
for entry in lst:
|
| 368 |
+
prnt(entry.as_c_expr())
|
| 369 |
+
prnt('};')
|
| 370 |
+
prnt()
|
| 371 |
+
#
|
| 372 |
+
# the declaration of '_cffi_includes'
|
| 373 |
+
if self.ffi._included_ffis:
|
| 374 |
+
prnt('static const char * const _cffi_includes[] = {')
|
| 375 |
+
for ffi_to_include in self.ffi._included_ffis:
|
| 376 |
+
try:
|
| 377 |
+
included_module_name, included_source = (
|
| 378 |
+
ffi_to_include._assigned_source[:2])
|
| 379 |
+
except AttributeError:
|
| 380 |
+
raise VerificationError(
|
| 381 |
+
"ffi object %r includes %r, but the latter has not "
|
| 382 |
+
"been prepared with set_source()" % (
|
| 383 |
+
self.ffi, ffi_to_include,))
|
| 384 |
+
if included_source is None:
|
| 385 |
+
raise VerificationError(
|
| 386 |
+
"not implemented yet: ffi.include() of a Python-based "
|
| 387 |
+
"ffi inside a C-based ffi")
|
| 388 |
+
prnt(' "%s",' % (included_module_name,))
|
| 389 |
+
prnt(' NULL')
|
| 390 |
+
prnt('};')
|
| 391 |
+
prnt()
|
| 392 |
+
#
|
| 393 |
+
# the declaration of '_cffi_type_context'
|
| 394 |
+
prnt('static const struct _cffi_type_context_s _cffi_type_context = {')
|
| 395 |
+
prnt(' _cffi_types,')
|
| 396 |
+
for step_name in self.ALL_STEPS:
|
| 397 |
+
if nums[step_name] > 0:
|
| 398 |
+
prnt(' _cffi_%ss,' % step_name)
|
| 399 |
+
else:
|
| 400 |
+
prnt(' NULL, /* no %ss */' % step_name)
|
| 401 |
+
for step_name in self.ALL_STEPS:
|
| 402 |
+
if step_name != "field":
|
| 403 |
+
prnt(' %d, /* num_%ss */' % (nums[step_name], step_name))
|
| 404 |
+
if self.ffi._included_ffis:
|
| 405 |
+
prnt(' _cffi_includes,')
|
| 406 |
+
else:
|
| 407 |
+
prnt(' NULL, /* no includes */')
|
| 408 |
+
prnt(' %d, /* num_types */' % (len(self.cffi_types),))
|
| 409 |
+
flags = 0
|
| 410 |
+
if self._num_externpy > 0 or self.ffi._embedding is not None:
|
| 411 |
+
flags |= 1 # set to mean that we use extern "Python"
|
| 412 |
+
prnt(' %d, /* flags */' % flags)
|
| 413 |
+
prnt('};')
|
| 414 |
+
prnt()
|
| 415 |
+
#
|
| 416 |
+
# the init function
|
| 417 |
+
prnt('#ifdef __GNUC__')
|
| 418 |
+
prnt('# pragma GCC visibility push(default) /* for -fvisibility= */')
|
| 419 |
+
prnt('#endif')
|
| 420 |
+
prnt()
|
| 421 |
+
prnt('#ifdef PYPY_VERSION')
|
| 422 |
+
prnt('PyMODINIT_FUNC')
|
| 423 |
+
prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,))
|
| 424 |
+
prnt('{')
|
| 425 |
+
if flags & 1:
|
| 426 |
+
prnt(' if (((intptr_t)p[0]) >= 0x0A03) {')
|
| 427 |
+
prnt(' _cffi_call_python_org = '
|
| 428 |
+
'(void(*)(struct _cffi_externpy_s *, char *))p[1];')
|
| 429 |
+
prnt(' }')
|
| 430 |
+
prnt(' p[0] = (const void *)0x%x;' % self._version)
|
| 431 |
+
prnt(' p[1] = &_cffi_type_context;')
|
| 432 |
+
prnt('#if PY_MAJOR_VERSION >= 3')
|
| 433 |
+
prnt(' return NULL;')
|
| 434 |
+
prnt('#endif')
|
| 435 |
+
prnt('}')
|
| 436 |
+
# on Windows, distutils insists on putting init_cffi_xyz in
|
| 437 |
+
# 'export_symbols', so instead of fighting it, just give up and
|
| 438 |
+
# give it one
|
| 439 |
+
prnt('# ifdef _MSC_VER')
|
| 440 |
+
prnt(' PyMODINIT_FUNC')
|
| 441 |
+
prnt('# if PY_MAJOR_VERSION >= 3')
|
| 442 |
+
prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,))
|
| 443 |
+
prnt('# else')
|
| 444 |
+
prnt(' init%s(void) { }' % (base_module_name,))
|
| 445 |
+
prnt('# endif')
|
| 446 |
+
prnt('# endif')
|
| 447 |
+
prnt('#elif PY_MAJOR_VERSION >= 3')
|
| 448 |
+
prnt('PyMODINIT_FUNC')
|
| 449 |
+
prnt('PyInit_%s(void)' % (base_module_name,))
|
| 450 |
+
prnt('{')
|
| 451 |
+
prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % (
|
| 452 |
+
self.module_name, self._version))
|
| 453 |
+
prnt('}')
|
| 454 |
+
prnt('#else')
|
| 455 |
+
prnt('PyMODINIT_FUNC')
|
| 456 |
+
prnt('init%s(void)' % (base_module_name,))
|
| 457 |
+
prnt('{')
|
| 458 |
+
prnt(' _cffi_init("%s", 0x%x, &_cffi_type_context);' % (
|
| 459 |
+
self.module_name, self._version))
|
| 460 |
+
prnt('}')
|
| 461 |
+
prnt('#endif')
|
| 462 |
+
prnt()
|
| 463 |
+
prnt('#ifdef __GNUC__')
|
| 464 |
+
prnt('# pragma GCC visibility pop')
|
| 465 |
+
prnt('#endif')
|
| 466 |
+
self._version = None
|
| 467 |
+
|
| 468 |
+
def _to_py(self, x):
|
| 469 |
+
if isinstance(x, str):
|
| 470 |
+
return "b'%s'" % (x,)
|
| 471 |
+
if isinstance(x, (list, tuple)):
|
| 472 |
+
rep = [self._to_py(item) for item in x]
|
| 473 |
+
if len(rep) == 1:
|
| 474 |
+
rep.append('')
|
| 475 |
+
return "(%s)" % (','.join(rep),)
|
| 476 |
+
return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp.
|
| 477 |
+
|
| 478 |
+
def write_py_source_to_f(self, f):
|
| 479 |
+
self._f = f
|
| 480 |
+
prnt = self._prnt
|
| 481 |
+
#
|
| 482 |
+
# header
|
| 483 |
+
prnt("# auto-generated file")
|
| 484 |
+
prnt("import _cffi_backend")
|
| 485 |
+
#
|
| 486 |
+
# the 'import' of the included ffis
|
| 487 |
+
num_includes = len(self.ffi._included_ffis or ())
|
| 488 |
+
for i in range(num_includes):
|
| 489 |
+
ffi_to_include = self.ffi._included_ffis[i]
|
| 490 |
+
try:
|
| 491 |
+
included_module_name, included_source = (
|
| 492 |
+
ffi_to_include._assigned_source[:2])
|
| 493 |
+
except AttributeError:
|
| 494 |
+
raise VerificationError(
|
| 495 |
+
"ffi object %r includes %r, but the latter has not "
|
| 496 |
+
"been prepared with set_source()" % (
|
| 497 |
+
self.ffi, ffi_to_include,))
|
| 498 |
+
if included_source is not None:
|
| 499 |
+
raise VerificationError(
|
| 500 |
+
"not implemented yet: ffi.include() of a C-based "
|
| 501 |
+
"ffi inside a Python-based ffi")
|
| 502 |
+
prnt('from %s import ffi as _ffi%d' % (included_module_name, i))
|
| 503 |
+
prnt()
|
| 504 |
+
prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,))
|
| 505 |
+
prnt(" _version = 0x%x," % (self._version,))
|
| 506 |
+
self._version = None
|
| 507 |
+
#
|
| 508 |
+
# the '_types' keyword argument
|
| 509 |
+
self.cffi_types = tuple(self.cffi_types) # don't change any more
|
| 510 |
+
types_lst = [op.as_python_bytes() for op in self.cffi_types]
|
| 511 |
+
prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),))
|
| 512 |
+
typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
|
| 513 |
+
#
|
| 514 |
+
# the keyword arguments from ALL_STEPS
|
| 515 |
+
for step_name in self.ALL_STEPS:
|
| 516 |
+
lst = self._lsts[step_name]
|
| 517 |
+
if len(lst) > 0 and step_name != "field":
|
| 518 |
+
prnt(' _%ss = %s,' % (step_name, self._to_py(lst)))
|
| 519 |
+
#
|
| 520 |
+
# the '_includes' keyword argument
|
| 521 |
+
if num_includes > 0:
|
| 522 |
+
prnt(' _includes = (%s,),' % (
|
| 523 |
+
', '.join(['_ffi%d' % i for i in range(num_includes)]),))
|
| 524 |
+
#
|
| 525 |
+
# the footer
|
| 526 |
+
prnt(')')
|
| 527 |
+
|
| 528 |
+
# ----------
|
| 529 |
+
|
| 530 |
+
def _gettypenum(self, type):
|
| 531 |
+
# a KeyError here is a bug. please report it! :-)
|
| 532 |
+
return self._typesdict[type]
|
| 533 |
+
|
| 534 |
+
def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):
|
| 535 |
+
extraarg = ''
|
| 536 |
+
if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type():
|
| 537 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
| 538 |
+
converter = '_cffi_to_c_int'
|
| 539 |
+
extraarg = ', %s' % tp.name
|
| 540 |
+
elif isinstance(tp, model.UnknownFloatType):
|
| 541 |
+
# don't check with is_float_type(): it may be a 'long
|
| 542 |
+
# double' here, and _cffi_to_c_double would loose precision
|
| 543 |
+
converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),)
|
| 544 |
+
else:
|
| 545 |
+
cname = tp.get_c_name('')
|
| 546 |
+
converter = '(%s)_cffi_to_c_%s' % (cname,
|
| 547 |
+
tp.name.replace(' ', '_'))
|
| 548 |
+
if cname in ('char16_t', 'char32_t'):
|
| 549 |
+
self.needs_version(VERSION_CHAR16CHAR32)
|
| 550 |
+
errvalue = '-1'
|
| 551 |
+
#
|
| 552 |
+
elif isinstance(tp, model.PointerType):
|
| 553 |
+
self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,
|
| 554 |
+
tovar, errcode)
|
| 555 |
+
return
|
| 556 |
+
#
|
| 557 |
+
elif (isinstance(tp, model.StructOrUnionOrEnum) or
|
| 558 |
+
isinstance(tp, model.BasePrimitiveType)):
|
| 559 |
+
# a struct (not a struct pointer) as a function argument;
|
| 560 |
+
# or, a complex (the same code works)
|
| 561 |
+
self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'
|
| 562 |
+
% (tovar, self._gettypenum(tp), fromvar))
|
| 563 |
+
self._prnt(' %s;' % errcode)
|
| 564 |
+
return
|
| 565 |
+
#
|
| 566 |
+
elif isinstance(tp, model.FunctionPtrType):
|
| 567 |
+
converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')
|
| 568 |
+
extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)
|
| 569 |
+
errvalue = 'NULL'
|
| 570 |
+
#
|
| 571 |
+
else:
|
| 572 |
+
raise NotImplementedError(tp)
|
| 573 |
+
#
|
| 574 |
+
self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))
|
| 575 |
+
self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (
|
| 576 |
+
tovar, tp.get_c_name(''), errvalue))
|
| 577 |
+
self._prnt(' %s;' % errcode)
|
| 578 |
+
|
| 579 |
+
def _extra_local_variables(self, tp, localvars, freelines):
|
| 580 |
+
if isinstance(tp, model.PointerType):
|
| 581 |
+
localvars.add('Py_ssize_t datasize')
|
| 582 |
+
localvars.add('struct _cffi_freeme_s *large_args_free = NULL')
|
| 583 |
+
freelines.add('if (large_args_free != NULL)'
|
| 584 |
+
' _cffi_free_array_arguments(large_args_free);')
|
| 585 |
+
|
| 586 |
+
def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):
|
| 587 |
+
self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')
|
| 588 |
+
self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (
|
| 589 |
+
self._gettypenum(tp), fromvar, tovar))
|
| 590 |
+
self._prnt(' if (datasize != 0) {')
|
| 591 |
+
self._prnt(' %s = ((size_t)datasize) <= 640 ? '
|
| 592 |
+
'(%s)alloca((size_t)datasize) : NULL;' % (
|
| 593 |
+
tovar, tp.get_c_name('')))
|
| 594 |
+
self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, '
|
| 595 |
+
'(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar))
|
| 596 |
+
self._prnt(' datasize, &large_args_free) < 0)')
|
| 597 |
+
self._prnt(' %s;' % errcode)
|
| 598 |
+
self._prnt(' }')
|
| 599 |
+
|
| 600 |
+
def _convert_expr_from_c(self, tp, var, context):
|
| 601 |
+
if isinstance(tp, model.BasePrimitiveType):
|
| 602 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
| 603 |
+
return '_cffi_from_c_int(%s, %s)' % (var, tp.name)
|
| 604 |
+
elif isinstance(tp, model.UnknownFloatType):
|
| 605 |
+
return '_cffi_from_c_double(%s)' % (var,)
|
| 606 |
+
elif tp.name != 'long double' and not tp.is_complex_type():
|
| 607 |
+
cname = tp.name.replace(' ', '_')
|
| 608 |
+
if cname in ('char16_t', 'char32_t'):
|
| 609 |
+
self.needs_version(VERSION_CHAR16CHAR32)
|
| 610 |
+
return '_cffi_from_c_%s(%s)' % (cname, var)
|
| 611 |
+
else:
|
| 612 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
| 613 |
+
var, self._gettypenum(tp))
|
| 614 |
+
elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):
|
| 615 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
| 616 |
+
var, self._gettypenum(tp))
|
| 617 |
+
elif isinstance(tp, model.ArrayType):
|
| 618 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
| 619 |
+
var, self._gettypenum(model.PointerType(tp.item)))
|
| 620 |
+
elif isinstance(tp, model.StructOrUnion):
|
| 621 |
+
if tp.fldnames is None:
|
| 622 |
+
raise TypeError("'%s' is used as %s, but is opaque" % (
|
| 623 |
+
tp._get_c_name(), context))
|
| 624 |
+
return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (
|
| 625 |
+
var, self._gettypenum(tp))
|
| 626 |
+
elif isinstance(tp, model.EnumType):
|
| 627 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
| 628 |
+
var, self._gettypenum(tp))
|
| 629 |
+
else:
|
| 630 |
+
raise NotImplementedError(tp)
|
| 631 |
+
|
| 632 |
+
# ----------
|
| 633 |
+
# typedefs
|
| 634 |
+
|
| 635 |
+
def _typedef_type(self, tp, name):
|
| 636 |
+
return self._global_type(tp, "(*(%s *)0)" % (name,))
|
| 637 |
+
|
| 638 |
+
def _generate_cpy_typedef_collecttype(self, tp, name):
|
| 639 |
+
self._do_collect_type(self._typedef_type(tp, name))
|
| 640 |
+
|
| 641 |
+
def _generate_cpy_typedef_decl(self, tp, name):
|
| 642 |
+
pass
|
| 643 |
+
|
| 644 |
+
def _typedef_ctx(self, tp, name):
|
| 645 |
+
type_index = self._typesdict[tp]
|
| 646 |
+
self._lsts["typename"].append(TypenameExpr(name, type_index))
|
| 647 |
+
|
| 648 |
+
def _generate_cpy_typedef_ctx(self, tp, name):
|
| 649 |
+
tp = self._typedef_type(tp, name)
|
| 650 |
+
self._typedef_ctx(tp, name)
|
| 651 |
+
if getattr(tp, "origin", None) == "unknown_type":
|
| 652 |
+
self._struct_ctx(tp, tp.name, approxname=None)
|
| 653 |
+
elif isinstance(tp, model.NamedPointerType):
|
| 654 |
+
self._struct_ctx(tp.totype, tp.totype.name, approxname=tp.name,
|
| 655 |
+
named_ptr=tp)
|
| 656 |
+
|
| 657 |
+
# ----------
|
| 658 |
+
# function declarations
|
| 659 |
+
|
| 660 |
+
def _generate_cpy_function_collecttype(self, tp, name):
|
| 661 |
+
self._do_collect_type(tp.as_raw_function())
|
| 662 |
+
if tp.ellipsis and not self.target_is_python:
|
| 663 |
+
self._do_collect_type(tp)
|
| 664 |
+
|
| 665 |
+
def _generate_cpy_function_decl(self, tp, name):
|
| 666 |
+
assert not self.target_is_python
|
| 667 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 668 |
+
if tp.ellipsis:
|
| 669 |
+
# cannot support vararg functions better than this: check for its
|
| 670 |
+
# exact type (including the fixed arguments), and build it as a
|
| 671 |
+
# constant function pointer (no CPython wrapper)
|
| 672 |
+
self._generate_cpy_constant_decl(tp, name)
|
| 673 |
+
return
|
| 674 |
+
prnt = self._prnt
|
| 675 |
+
numargs = len(tp.args)
|
| 676 |
+
if numargs == 0:
|
| 677 |
+
argname = 'noarg'
|
| 678 |
+
elif numargs == 1:
|
| 679 |
+
argname = 'arg0'
|
| 680 |
+
else:
|
| 681 |
+
argname = 'args'
|
| 682 |
+
#
|
| 683 |
+
# ------------------------------
|
| 684 |
+
# the 'd' version of the function, only for addressof(lib, 'func')
|
| 685 |
+
arguments = []
|
| 686 |
+
call_arguments = []
|
| 687 |
+
context = 'argument of %s' % name
|
| 688 |
+
for i, type in enumerate(tp.args):
|
| 689 |
+
arguments.append(type.get_c_name(' x%d' % i, context))
|
| 690 |
+
call_arguments.append('x%d' % i)
|
| 691 |
+
repr_arguments = ', '.join(arguments)
|
| 692 |
+
repr_arguments = repr_arguments or 'void'
|
| 693 |
+
if tp.abi:
|
| 694 |
+
abi = tp.abi + ' '
|
| 695 |
+
else:
|
| 696 |
+
abi = ''
|
| 697 |
+
name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments)
|
| 698 |
+
prnt('static %s' % (tp.result.get_c_name(name_and_arguments),))
|
| 699 |
+
prnt('{')
|
| 700 |
+
call_arguments = ', '.join(call_arguments)
|
| 701 |
+
result_code = 'return '
|
| 702 |
+
if isinstance(tp.result, model.VoidType):
|
| 703 |
+
result_code = ''
|
| 704 |
+
prnt(' %s%s(%s);' % (result_code, name, call_arguments))
|
| 705 |
+
prnt('}')
|
| 706 |
+
#
|
| 707 |
+
prnt('#ifndef PYPY_VERSION') # ------------------------------
|
| 708 |
+
#
|
| 709 |
+
prnt('static PyObject *')
|
| 710 |
+
prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))
|
| 711 |
+
prnt('{')
|
| 712 |
+
#
|
| 713 |
+
context = 'argument of %s' % name
|
| 714 |
+
for i, type in enumerate(tp.args):
|
| 715 |
+
arg = type.get_c_name(' x%d' % i, context)
|
| 716 |
+
prnt(' %s;' % arg)
|
| 717 |
+
#
|
| 718 |
+
localvars = set()
|
| 719 |
+
freelines = set()
|
| 720 |
+
for type in tp.args:
|
| 721 |
+
self._extra_local_variables(type, localvars, freelines)
|
| 722 |
+
for decl in sorted(localvars):
|
| 723 |
+
prnt(' %s;' % (decl,))
|
| 724 |
+
#
|
| 725 |
+
if not isinstance(tp.result, model.VoidType):
|
| 726 |
+
result_code = 'result = '
|
| 727 |
+
context = 'result of %s' % name
|
| 728 |
+
result_decl = ' %s;' % tp.result.get_c_name(' result', context)
|
| 729 |
+
prnt(result_decl)
|
| 730 |
+
prnt(' PyObject *pyresult;')
|
| 731 |
+
else:
|
| 732 |
+
result_decl = None
|
| 733 |
+
result_code = ''
|
| 734 |
+
#
|
| 735 |
+
if len(tp.args) > 1:
|
| 736 |
+
rng = range(len(tp.args))
|
| 737 |
+
for i in rng:
|
| 738 |
+
prnt(' PyObject *arg%d;' % i)
|
| 739 |
+
prnt()
|
| 740 |
+
prnt(' if (!PyArg_UnpackTuple(args, "%s", %d, %d, %s))' % (
|
| 741 |
+
name, len(rng), len(rng),
|
| 742 |
+
', '.join(['&arg%d' % i for i in rng])))
|
| 743 |
+
prnt(' return NULL;')
|
| 744 |
+
prnt()
|
| 745 |
+
#
|
| 746 |
+
for i, type in enumerate(tp.args):
|
| 747 |
+
self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,
|
| 748 |
+
'return NULL')
|
| 749 |
+
prnt()
|
| 750 |
+
#
|
| 751 |
+
prnt(' Py_BEGIN_ALLOW_THREADS')
|
| 752 |
+
prnt(' _cffi_restore_errno();')
|
| 753 |
+
call_arguments = ['x%d' % i for i in range(len(tp.args))]
|
| 754 |
+
call_arguments = ', '.join(call_arguments)
|
| 755 |
+
prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
|
| 756 |
+
prnt(' _cffi_save_errno();')
|
| 757 |
+
prnt(' Py_END_ALLOW_THREADS')
|
| 758 |
+
prnt()
|
| 759 |
+
#
|
| 760 |
+
prnt(' (void)self; /* unused */')
|
| 761 |
+
if numargs == 0:
|
| 762 |
+
prnt(' (void)noarg; /* unused */')
|
| 763 |
+
if result_code:
|
| 764 |
+
prnt(' pyresult = %s;' %
|
| 765 |
+
self._convert_expr_from_c(tp.result, 'result', 'result type'))
|
| 766 |
+
for freeline in freelines:
|
| 767 |
+
prnt(' ' + freeline)
|
| 768 |
+
prnt(' return pyresult;')
|
| 769 |
+
else:
|
| 770 |
+
for freeline in freelines:
|
| 771 |
+
prnt(' ' + freeline)
|
| 772 |
+
prnt(' Py_INCREF(Py_None);')
|
| 773 |
+
prnt(' return Py_None;')
|
| 774 |
+
prnt('}')
|
| 775 |
+
#
|
| 776 |
+
prnt('#else') # ------------------------------
|
| 777 |
+
#
|
| 778 |
+
# the PyPy version: need to replace struct/union arguments with
|
| 779 |
+
# pointers, and if the result is a struct/union, insert a first
|
| 780 |
+
# arg that is a pointer to the result. We also do that for
|
| 781 |
+
# complex args and return type.
|
| 782 |
+
def need_indirection(type):
|
| 783 |
+
return (isinstance(type, model.StructOrUnion) or
|
| 784 |
+
(isinstance(type, model.PrimitiveType) and
|
| 785 |
+
type.is_complex_type()))
|
| 786 |
+
difference = False
|
| 787 |
+
arguments = []
|
| 788 |
+
call_arguments = []
|
| 789 |
+
context = 'argument of %s' % name
|
| 790 |
+
for i, type in enumerate(tp.args):
|
| 791 |
+
indirection = ''
|
| 792 |
+
if need_indirection(type):
|
| 793 |
+
indirection = '*'
|
| 794 |
+
difference = True
|
| 795 |
+
arg = type.get_c_name(' %sx%d' % (indirection, i), context)
|
| 796 |
+
arguments.append(arg)
|
| 797 |
+
call_arguments.append('%sx%d' % (indirection, i))
|
| 798 |
+
tp_result = tp.result
|
| 799 |
+
if need_indirection(tp_result):
|
| 800 |
+
context = 'result of %s' % name
|
| 801 |
+
arg = tp_result.get_c_name(' *result', context)
|
| 802 |
+
arguments.insert(0, arg)
|
| 803 |
+
tp_result = model.void_type
|
| 804 |
+
result_decl = None
|
| 805 |
+
result_code = '*result = '
|
| 806 |
+
difference = True
|
| 807 |
+
if difference:
|
| 808 |
+
repr_arguments = ', '.join(arguments)
|
| 809 |
+
repr_arguments = repr_arguments or 'void'
|
| 810 |
+
name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name,
|
| 811 |
+
repr_arguments)
|
| 812 |
+
prnt('static %s' % (tp_result.get_c_name(name_and_arguments),))
|
| 813 |
+
prnt('{')
|
| 814 |
+
if result_decl:
|
| 815 |
+
prnt(result_decl)
|
| 816 |
+
call_arguments = ', '.join(call_arguments)
|
| 817 |
+
prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
|
| 818 |
+
if result_decl:
|
| 819 |
+
prnt(' return result;')
|
| 820 |
+
prnt('}')
|
| 821 |
+
else:
|
| 822 |
+
prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name))
|
| 823 |
+
#
|
| 824 |
+
prnt('#endif') # ------------------------------
|
| 825 |
+
prnt()
|
| 826 |
+
|
| 827 |
+
def _generate_cpy_function_ctx(self, tp, name):
|
| 828 |
+
if tp.ellipsis and not self.target_is_python:
|
| 829 |
+
self._generate_cpy_constant_ctx(tp, name)
|
| 830 |
+
return
|
| 831 |
+
type_index = self._typesdict[tp.as_raw_function()]
|
| 832 |
+
numargs = len(tp.args)
|
| 833 |
+
if self.target_is_python:
|
| 834 |
+
meth_kind = OP_DLOPEN_FUNC
|
| 835 |
+
elif numargs == 0:
|
| 836 |
+
meth_kind = OP_CPYTHON_BLTN_N # 'METH_NOARGS'
|
| 837 |
+
elif numargs == 1:
|
| 838 |
+
meth_kind = OP_CPYTHON_BLTN_O # 'METH_O'
|
| 839 |
+
else:
|
| 840 |
+
meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS'
|
| 841 |
+
self._lsts["global"].append(
|
| 842 |
+
GlobalExpr(name, '_cffi_f_%s' % name,
|
| 843 |
+
CffiOp(meth_kind, type_index),
|
| 844 |
+
size='_cffi_d_%s' % name))
|
| 845 |
+
|
| 846 |
+
# ----------
|
| 847 |
+
# named structs or unions
|
| 848 |
+
|
| 849 |
+
def _field_type(self, tp_struct, field_name, tp_field):
|
| 850 |
+
if isinstance(tp_field, model.ArrayType):
|
| 851 |
+
actual_length = tp_field.length
|
| 852 |
+
if actual_length == '...':
|
| 853 |
+
ptr_struct_name = tp_struct.get_c_name('*')
|
| 854 |
+
actual_length = '_cffi_array_len(((%s)0)->%s)' % (
|
| 855 |
+
ptr_struct_name, field_name)
|
| 856 |
+
tp_item = self._field_type(tp_struct, '%s[0]' % field_name,
|
| 857 |
+
tp_field.item)
|
| 858 |
+
tp_field = model.ArrayType(tp_item, actual_length)
|
| 859 |
+
return tp_field
|
| 860 |
+
|
| 861 |
+
def _struct_collecttype(self, tp):
|
| 862 |
+
self._do_collect_type(tp)
|
| 863 |
+
if self.target_is_python:
|
| 864 |
+
# also requires nested anon struct/unions in ABI mode, recursively
|
| 865 |
+
for fldtype in tp.anonymous_struct_fields():
|
| 866 |
+
self._struct_collecttype(fldtype)
|
| 867 |
+
|
| 868 |
+
def _struct_decl(self, tp, cname, approxname):
|
| 869 |
+
if tp.fldtypes is None:
|
| 870 |
+
return
|
| 871 |
+
prnt = self._prnt
|
| 872 |
+
checkfuncname = '_cffi_checkfld_%s' % (approxname,)
|
| 873 |
+
prnt('_CFFI_UNUSED_FN')
|
| 874 |
+
prnt('static void %s(%s *p)' % (checkfuncname, cname))
|
| 875 |
+
prnt('{')
|
| 876 |
+
prnt(' /* only to generate compile-time warnings or errors */')
|
| 877 |
+
prnt(' (void)p;')
|
| 878 |
+
for fname, ftype, fbitsize, fqual in self._enum_fields(tp):
|
| 879 |
+
try:
|
| 880 |
+
if ftype.is_integer_type() or fbitsize >= 0:
|
| 881 |
+
# accept all integers, but complain on float or double
|
| 882 |
+
if fname != '':
|
| 883 |
+
prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is "
|
| 884 |
+
"an integer */" % (fname, cname, fname))
|
| 885 |
+
continue
|
| 886 |
+
# only accept exactly the type declared, except that '[]'
|
| 887 |
+
# is interpreted as a '*' and so will match any array length.
|
| 888 |
+
# (It would also match '*', but that's harder to detect...)
|
| 889 |
+
while (isinstance(ftype, model.ArrayType)
|
| 890 |
+
and (ftype.length is None or ftype.length == '...')):
|
| 891 |
+
ftype = ftype.item
|
| 892 |
+
fname = fname + '[0]'
|
| 893 |
+
prnt(' { %s = &p->%s; (void)tmp; }' % (
|
| 894 |
+
ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
|
| 895 |
+
fname))
|
| 896 |
+
except VerificationError as e:
|
| 897 |
+
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
|
| 898 |
+
prnt('}')
|
| 899 |
+
prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname))
|
| 900 |
+
prnt()
|
| 901 |
+
|
| 902 |
+
def _struct_ctx(self, tp, cname, approxname, named_ptr=None):
|
| 903 |
+
type_index = self._typesdict[tp]
|
| 904 |
+
reason_for_not_expanding = None
|
| 905 |
+
flags = []
|
| 906 |
+
if isinstance(tp, model.UnionType):
|
| 907 |
+
flags.append("_CFFI_F_UNION")
|
| 908 |
+
if tp.fldtypes is None:
|
| 909 |
+
flags.append("_CFFI_F_OPAQUE")
|
| 910 |
+
reason_for_not_expanding = "opaque"
|
| 911 |
+
if (tp not in self.ffi._parser._included_declarations and
|
| 912 |
+
(named_ptr is None or
|
| 913 |
+
named_ptr not in self.ffi._parser._included_declarations)):
|
| 914 |
+
if tp.fldtypes is None:
|
| 915 |
+
pass # opaque
|
| 916 |
+
elif tp.partial or any(tp.anonymous_struct_fields()):
|
| 917 |
+
pass # field layout obtained silently from the C compiler
|
| 918 |
+
else:
|
| 919 |
+
flags.append("_CFFI_F_CHECK_FIELDS")
|
| 920 |
+
if tp.packed:
|
| 921 |
+
if tp.packed > 1:
|
| 922 |
+
raise NotImplementedError(
|
| 923 |
+
"%r is declared with 'pack=%r'; only 0 or 1 are "
|
| 924 |
+
"supported in API mode (try to use \"...;\", which "
|
| 925 |
+
"does not require a 'pack' declaration)" %
|
| 926 |
+
(tp, tp.packed))
|
| 927 |
+
flags.append("_CFFI_F_PACKED")
|
| 928 |
+
else:
|
| 929 |
+
flags.append("_CFFI_F_EXTERNAL")
|
| 930 |
+
reason_for_not_expanding = "external"
|
| 931 |
+
flags = '|'.join(flags) or '0'
|
| 932 |
+
c_fields = []
|
| 933 |
+
if reason_for_not_expanding is None:
|
| 934 |
+
enumfields = list(self._enum_fields(tp))
|
| 935 |
+
for fldname, fldtype, fbitsize, fqual in enumfields:
|
| 936 |
+
fldtype = self._field_type(tp, fldname, fldtype)
|
| 937 |
+
self._check_not_opaque(fldtype,
|
| 938 |
+
"field '%s.%s'" % (tp.name, fldname))
|
| 939 |
+
# cname is None for _add_missing_struct_unions() only
|
| 940 |
+
op = OP_NOOP
|
| 941 |
+
if fbitsize >= 0:
|
| 942 |
+
op = OP_BITFIELD
|
| 943 |
+
size = '%d /* bits */' % fbitsize
|
| 944 |
+
elif cname is None or (
|
| 945 |
+
isinstance(fldtype, model.ArrayType) and
|
| 946 |
+
fldtype.length is None):
|
| 947 |
+
size = '(size_t)-1'
|
| 948 |
+
else:
|
| 949 |
+
size = 'sizeof(((%s)0)->%s)' % (
|
| 950 |
+
tp.get_c_name('*') if named_ptr is None
|
| 951 |
+
else named_ptr.name,
|
| 952 |
+
fldname)
|
| 953 |
+
if cname is None or fbitsize >= 0:
|
| 954 |
+
offset = '(size_t)-1'
|
| 955 |
+
elif named_ptr is not None:
|
| 956 |
+
offset = '(size_t)(((char *)&((%s)4096)->%s) - (char *)4096)' % (
|
| 957 |
+
named_ptr.name, fldname)
|
| 958 |
+
else:
|
| 959 |
+
offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname)
|
| 960 |
+
c_fields.append(
|
| 961 |
+
FieldExpr(fldname, offset, size, fbitsize,
|
| 962 |
+
CffiOp(op, self._typesdict[fldtype])))
|
| 963 |
+
first_field_index = len(self._lsts["field"])
|
| 964 |
+
self._lsts["field"].extend(c_fields)
|
| 965 |
+
#
|
| 966 |
+
if cname is None: # unknown name, for _add_missing_struct_unions
|
| 967 |
+
size = '(size_t)-2'
|
| 968 |
+
align = -2
|
| 969 |
+
comment = "unnamed"
|
| 970 |
+
else:
|
| 971 |
+
if named_ptr is not None:
|
| 972 |
+
size = 'sizeof(*(%s)0)' % (named_ptr.name,)
|
| 973 |
+
align = '-1 /* unknown alignment */'
|
| 974 |
+
else:
|
| 975 |
+
size = 'sizeof(%s)' % (cname,)
|
| 976 |
+
align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,)
|
| 977 |
+
comment = None
|
| 978 |
+
else:
|
| 979 |
+
size = '(size_t)-1'
|
| 980 |
+
align = -1
|
| 981 |
+
first_field_index = -1
|
| 982 |
+
comment = reason_for_not_expanding
|
| 983 |
+
self._lsts["struct_union"].append(
|
| 984 |
+
StructUnionExpr(tp.name, type_index, flags, size, align, comment,
|
| 985 |
+
first_field_index, c_fields))
|
| 986 |
+
self._seen_struct_unions.add(tp)
|
| 987 |
+
|
| 988 |
+
def _check_not_opaque(self, tp, location):
|
| 989 |
+
while isinstance(tp, model.ArrayType):
|
| 990 |
+
tp = tp.item
|
| 991 |
+
if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None:
|
| 992 |
+
raise TypeError(
|
| 993 |
+
"%s is of an opaque type (not declared in cdef())" % location)
|
| 994 |
+
|
| 995 |
+
def _add_missing_struct_unions(self):
|
| 996 |
+
# not very nice, but some struct declarations might be missing
|
| 997 |
+
# because they don't have any known C name. Check that they are
|
| 998 |
+
# not partial (we can't complete or verify them!) and emit them
|
| 999 |
+
# anonymously.
|
| 1000 |
+
lst = list(self._struct_unions.items())
|
| 1001 |
+
lst.sort(key=lambda tp_order: tp_order[1])
|
| 1002 |
+
for tp, order in lst:
|
| 1003 |
+
if tp not in self._seen_struct_unions:
|
| 1004 |
+
if tp.partial:
|
| 1005 |
+
raise NotImplementedError("internal inconsistency: %r is "
|
| 1006 |
+
"partial but was not seen at "
|
| 1007 |
+
"this point" % (tp,))
|
| 1008 |
+
if tp.name.startswith('$') and tp.name[1:].isdigit():
|
| 1009 |
+
approxname = tp.name[1:]
|
| 1010 |
+
elif tp.name == '_IO_FILE' and tp.forcename == 'FILE':
|
| 1011 |
+
approxname = 'FILE'
|
| 1012 |
+
self._typedef_ctx(tp, 'FILE')
|
| 1013 |
+
else:
|
| 1014 |
+
raise NotImplementedError("internal inconsistency: %r" %
|
| 1015 |
+
(tp,))
|
| 1016 |
+
self._struct_ctx(tp, None, approxname)
|
| 1017 |
+
|
| 1018 |
+
def _generate_cpy_struct_collecttype(self, tp, name):
|
| 1019 |
+
self._struct_collecttype(tp)
|
| 1020 |
+
_generate_cpy_union_collecttype = _generate_cpy_struct_collecttype
|
| 1021 |
+
|
| 1022 |
+
def _struct_names(self, tp):
|
| 1023 |
+
cname = tp.get_c_name('')
|
| 1024 |
+
if ' ' in cname:
|
| 1025 |
+
return cname, cname.replace(' ', '_')
|
| 1026 |
+
else:
|
| 1027 |
+
return cname, '_' + cname
|
| 1028 |
+
|
| 1029 |
+
def _generate_cpy_struct_decl(self, tp, name):
|
| 1030 |
+
self._struct_decl(tp, *self._struct_names(tp))
|
| 1031 |
+
_generate_cpy_union_decl = _generate_cpy_struct_decl
|
| 1032 |
+
|
| 1033 |
+
def _generate_cpy_struct_ctx(self, tp, name):
|
| 1034 |
+
self._struct_ctx(tp, *self._struct_names(tp))
|
| 1035 |
+
_generate_cpy_union_ctx = _generate_cpy_struct_ctx
|
| 1036 |
+
|
| 1037 |
+
# ----------
|
| 1038 |
+
# 'anonymous' declarations. These are produced for anonymous structs
|
| 1039 |
+
# or unions; the 'name' is obtained by a typedef.
|
| 1040 |
+
|
| 1041 |
+
def _generate_cpy_anonymous_collecttype(self, tp, name):
|
| 1042 |
+
if isinstance(tp, model.EnumType):
|
| 1043 |
+
self._generate_cpy_enum_collecttype(tp, name)
|
| 1044 |
+
else:
|
| 1045 |
+
self._struct_collecttype(tp)
|
| 1046 |
+
|
| 1047 |
+
def _generate_cpy_anonymous_decl(self, tp, name):
|
| 1048 |
+
if isinstance(tp, model.EnumType):
|
| 1049 |
+
self._generate_cpy_enum_decl(tp)
|
| 1050 |
+
else:
|
| 1051 |
+
self._struct_decl(tp, name, 'typedef_' + name)
|
| 1052 |
+
|
| 1053 |
+
def _generate_cpy_anonymous_ctx(self, tp, name):
|
| 1054 |
+
if isinstance(tp, model.EnumType):
|
| 1055 |
+
self._enum_ctx(tp, name)
|
| 1056 |
+
else:
|
| 1057 |
+
self._struct_ctx(tp, name, 'typedef_' + name)
|
| 1058 |
+
|
| 1059 |
+
# ----------
|
| 1060 |
+
# constants, declared with "static const ..."
|
| 1061 |
+
|
| 1062 |
+
def _generate_cpy_const(self, is_int, name, tp=None, category='const',
|
| 1063 |
+
check_value=None):
|
| 1064 |
+
if (category, name) in self._seen_constants:
|
| 1065 |
+
raise VerificationError(
|
| 1066 |
+
"duplicate declaration of %s '%s'" % (category, name))
|
| 1067 |
+
self._seen_constants.add((category, name))
|
| 1068 |
+
#
|
| 1069 |
+
prnt = self._prnt
|
| 1070 |
+
funcname = '_cffi_%s_%s' % (category, name)
|
| 1071 |
+
if is_int:
|
| 1072 |
+
prnt('static int %s(unsigned long long *o)' % funcname)
|
| 1073 |
+
prnt('{')
|
| 1074 |
+
prnt(' int n = (%s) <= 0;' % (name,))
|
| 1075 |
+
prnt(' *o = (unsigned long long)((%s) | 0);'
|
| 1076 |
+
' /* check that %s is an integer */' % (name, name))
|
| 1077 |
+
if check_value is not None:
|
| 1078 |
+
if check_value > 0:
|
| 1079 |
+
check_value = '%dU' % (check_value,)
|
| 1080 |
+
prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,))
|
| 1081 |
+
prnt(' n |= 2;')
|
| 1082 |
+
prnt(' return n;')
|
| 1083 |
+
prnt('}')
|
| 1084 |
+
else:
|
| 1085 |
+
assert check_value is None
|
| 1086 |
+
prnt('static void %s(char *o)' % funcname)
|
| 1087 |
+
prnt('{')
|
| 1088 |
+
prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name))
|
| 1089 |
+
prnt('}')
|
| 1090 |
+
prnt()
|
| 1091 |
+
|
| 1092 |
+
def _generate_cpy_constant_collecttype(self, tp, name):
|
| 1093 |
+
is_int = tp.is_integer_type()
|
| 1094 |
+
if not is_int or self.target_is_python:
|
| 1095 |
+
self._do_collect_type(tp)
|
| 1096 |
+
|
| 1097 |
+
def _generate_cpy_constant_decl(self, tp, name):
|
| 1098 |
+
is_int = tp.is_integer_type()
|
| 1099 |
+
self._generate_cpy_const(is_int, name, tp)
|
| 1100 |
+
|
| 1101 |
+
def _generate_cpy_constant_ctx(self, tp, name):
|
| 1102 |
+
if not self.target_is_python and tp.is_integer_type():
|
| 1103 |
+
type_op = CffiOp(OP_CONSTANT_INT, -1)
|
| 1104 |
+
else:
|
| 1105 |
+
if self.target_is_python:
|
| 1106 |
+
const_kind = OP_DLOPEN_CONST
|
| 1107 |
+
else:
|
| 1108 |
+
const_kind = OP_CONSTANT
|
| 1109 |
+
type_index = self._typesdict[tp]
|
| 1110 |
+
type_op = CffiOp(const_kind, type_index)
|
| 1111 |
+
self._lsts["global"].append(
|
| 1112 |
+
GlobalExpr(name, '_cffi_const_%s' % name, type_op))
|
| 1113 |
+
|
| 1114 |
+
# ----------
|
| 1115 |
+
# enums
|
| 1116 |
+
|
| 1117 |
+
def _generate_cpy_enum_collecttype(self, tp, name):
|
| 1118 |
+
self._do_collect_type(tp)
|
| 1119 |
+
|
| 1120 |
+
def _generate_cpy_enum_decl(self, tp, name=None):
|
| 1121 |
+
for enumerator in tp.enumerators:
|
| 1122 |
+
self._generate_cpy_const(True, enumerator)
|
| 1123 |
+
|
| 1124 |
+
def _enum_ctx(self, tp, cname):
|
| 1125 |
+
type_index = self._typesdict[tp]
|
| 1126 |
+
type_op = CffiOp(OP_ENUM, -1)
|
| 1127 |
+
if self.target_is_python:
|
| 1128 |
+
tp.check_not_partial()
|
| 1129 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
| 1130 |
+
self._lsts["global"].append(
|
| 1131 |
+
GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op,
|
| 1132 |
+
check_value=enumvalue))
|
| 1133 |
+
#
|
| 1134 |
+
if cname is not None and '$' not in cname and not self.target_is_python:
|
| 1135 |
+
size = "sizeof(%s)" % cname
|
| 1136 |
+
signed = "((%s)-1) <= 0" % cname
|
| 1137 |
+
else:
|
| 1138 |
+
basetp = tp.build_baseinttype(self.ffi, [])
|
| 1139 |
+
size = self.ffi.sizeof(basetp)
|
| 1140 |
+
signed = int(int(self.ffi.cast(basetp, -1)) < 0)
|
| 1141 |
+
allenums = ",".join(tp.enumerators)
|
| 1142 |
+
self._lsts["enum"].append(
|
| 1143 |
+
EnumExpr(tp.name, type_index, size, signed, allenums))
|
| 1144 |
+
|
| 1145 |
+
def _generate_cpy_enum_ctx(self, tp, name):
|
| 1146 |
+
self._enum_ctx(tp, tp._get_c_name())
|
| 1147 |
+
|
| 1148 |
+
# ----------
|
| 1149 |
+
# macros: for now only for integers
|
| 1150 |
+
|
| 1151 |
+
def _generate_cpy_macro_collecttype(self, tp, name):
|
| 1152 |
+
pass
|
| 1153 |
+
|
| 1154 |
+
def _generate_cpy_macro_decl(self, tp, name):
|
| 1155 |
+
if tp == '...':
|
| 1156 |
+
check_value = None
|
| 1157 |
+
else:
|
| 1158 |
+
check_value = tp # an integer
|
| 1159 |
+
self._generate_cpy_const(True, name, check_value=check_value)
|
| 1160 |
+
|
| 1161 |
+
def _generate_cpy_macro_ctx(self, tp, name):
|
| 1162 |
+
if tp == '...':
|
| 1163 |
+
if self.target_is_python:
|
| 1164 |
+
raise VerificationError(
|
| 1165 |
+
"cannot use the syntax '...' in '#define %s ...' when "
|
| 1166 |
+
"using the ABI mode" % (name,))
|
| 1167 |
+
check_value = None
|
| 1168 |
+
else:
|
| 1169 |
+
check_value = tp # an integer
|
| 1170 |
+
type_op = CffiOp(OP_CONSTANT_INT, -1)
|
| 1171 |
+
self._lsts["global"].append(
|
| 1172 |
+
GlobalExpr(name, '_cffi_const_%s' % name, type_op,
|
| 1173 |
+
check_value=check_value))
|
| 1174 |
+
|
| 1175 |
+
# ----------
|
| 1176 |
+
# global variables
|
| 1177 |
+
|
| 1178 |
+
def _global_type(self, tp, global_name):
|
| 1179 |
+
if isinstance(tp, model.ArrayType):
|
| 1180 |
+
actual_length = tp.length
|
| 1181 |
+
if actual_length == '...':
|
| 1182 |
+
actual_length = '_cffi_array_len(%s)' % (global_name,)
|
| 1183 |
+
tp_item = self._global_type(tp.item, '%s[0]' % global_name)
|
| 1184 |
+
tp = model.ArrayType(tp_item, actual_length)
|
| 1185 |
+
return tp
|
| 1186 |
+
|
| 1187 |
+
def _generate_cpy_variable_collecttype(self, tp, name):
|
| 1188 |
+
self._do_collect_type(self._global_type(tp, name))
|
| 1189 |
+
|
| 1190 |
+
def _generate_cpy_variable_decl(self, tp, name):
|
| 1191 |
+
prnt = self._prnt
|
| 1192 |
+
tp = self._global_type(tp, name)
|
| 1193 |
+
if isinstance(tp, model.ArrayType) and tp.length is None:
|
| 1194 |
+
tp = tp.item
|
| 1195 |
+
ampersand = ''
|
| 1196 |
+
else:
|
| 1197 |
+
ampersand = '&'
|
| 1198 |
+
# This code assumes that casts from "tp *" to "void *" is a
|
| 1199 |
+
# no-op, i.e. a function that returns a "tp *" can be called
|
| 1200 |
+
# as if it returned a "void *". This should be generally true
|
| 1201 |
+
# on any modern machine. The only exception to that rule (on
|
| 1202 |
+
# uncommon architectures, and as far as I can tell) might be
|
| 1203 |
+
# if 'tp' were a function type, but that is not possible here.
|
| 1204 |
+
# (If 'tp' is a function _pointer_ type, then casts from "fn_t
|
| 1205 |
+
# **" to "void *" are again no-ops, as far as I can tell.)
|
| 1206 |
+
decl = '*_cffi_var_%s(void)' % (name,)
|
| 1207 |
+
prnt('static ' + tp.get_c_name(decl, quals=self._current_quals))
|
| 1208 |
+
prnt('{')
|
| 1209 |
+
prnt(' return %s(%s);' % (ampersand, name))
|
| 1210 |
+
prnt('}')
|
| 1211 |
+
prnt()
|
| 1212 |
+
|
| 1213 |
+
def _generate_cpy_variable_ctx(self, tp, name):
|
| 1214 |
+
tp = self._global_type(tp, name)
|
| 1215 |
+
type_index = self._typesdict[tp]
|
| 1216 |
+
if self.target_is_python:
|
| 1217 |
+
op = OP_GLOBAL_VAR
|
| 1218 |
+
else:
|
| 1219 |
+
op = OP_GLOBAL_VAR_F
|
| 1220 |
+
self._lsts["global"].append(
|
| 1221 |
+
GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index)))
|
| 1222 |
+
|
| 1223 |
+
# ----------
|
| 1224 |
+
# extern "Python"
|
| 1225 |
+
|
| 1226 |
+
def _generate_cpy_extern_python_collecttype(self, tp, name):
|
| 1227 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 1228 |
+
self._do_collect_type(tp)
|
| 1229 |
+
_generate_cpy_dllexport_python_collecttype = \
|
| 1230 |
+
_generate_cpy_extern_python_plus_c_collecttype = \
|
| 1231 |
+
_generate_cpy_extern_python_collecttype
|
| 1232 |
+
|
| 1233 |
+
def _extern_python_decl(self, tp, name, tag_and_space):
|
| 1234 |
+
prnt = self._prnt
|
| 1235 |
+
if isinstance(tp.result, model.VoidType):
|
| 1236 |
+
size_of_result = '0'
|
| 1237 |
+
else:
|
| 1238 |
+
context = 'result of %s' % name
|
| 1239 |
+
size_of_result = '(int)sizeof(%s)' % (
|
| 1240 |
+
tp.result.get_c_name('', context),)
|
| 1241 |
+
prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name)
|
| 1242 |
+
prnt(' { "%s.%s", %s, 0, 0 };' % (
|
| 1243 |
+
self.module_name, name, size_of_result))
|
| 1244 |
+
prnt()
|
| 1245 |
+
#
|
| 1246 |
+
arguments = []
|
| 1247 |
+
context = 'argument of %s' % name
|
| 1248 |
+
for i, type in enumerate(tp.args):
|
| 1249 |
+
arg = type.get_c_name(' a%d' % i, context)
|
| 1250 |
+
arguments.append(arg)
|
| 1251 |
+
#
|
| 1252 |
+
repr_arguments = ', '.join(arguments)
|
| 1253 |
+
repr_arguments = repr_arguments or 'void'
|
| 1254 |
+
name_and_arguments = '%s(%s)' % (name, repr_arguments)
|
| 1255 |
+
if tp.abi == "__stdcall":
|
| 1256 |
+
name_and_arguments = '_cffi_stdcall ' + name_and_arguments
|
| 1257 |
+
#
|
| 1258 |
+
def may_need_128_bits(tp):
|
| 1259 |
+
return (isinstance(tp, model.PrimitiveType) and
|
| 1260 |
+
tp.name == 'long double')
|
| 1261 |
+
#
|
| 1262 |
+
size_of_a = max(len(tp.args)*8, 8)
|
| 1263 |
+
if may_need_128_bits(tp.result):
|
| 1264 |
+
size_of_a = max(size_of_a, 16)
|
| 1265 |
+
if isinstance(tp.result, model.StructOrUnion):
|
| 1266 |
+
size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % (
|
| 1267 |
+
tp.result.get_c_name(''), size_of_a,
|
| 1268 |
+
tp.result.get_c_name(''), size_of_a)
|
| 1269 |
+
prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments)))
|
| 1270 |
+
prnt('{')
|
| 1271 |
+
prnt(' char a[%s];' % size_of_a)
|
| 1272 |
+
prnt(' char *p = a;')
|
| 1273 |
+
for i, type in enumerate(tp.args):
|
| 1274 |
+
arg = 'a%d' % i
|
| 1275 |
+
if (isinstance(type, model.StructOrUnion) or
|
| 1276 |
+
may_need_128_bits(type)):
|
| 1277 |
+
arg = '&' + arg
|
| 1278 |
+
type = model.PointerType(type)
|
| 1279 |
+
prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg))
|
| 1280 |
+
prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name)
|
| 1281 |
+
if not isinstance(tp.result, model.VoidType):
|
| 1282 |
+
prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),))
|
| 1283 |
+
prnt('}')
|
| 1284 |
+
prnt()
|
| 1285 |
+
self._num_externpy += 1
|
| 1286 |
+
|
| 1287 |
+
def _generate_cpy_extern_python_decl(self, tp, name):
|
| 1288 |
+
self._extern_python_decl(tp, name, 'static ')
|
| 1289 |
+
|
| 1290 |
+
def _generate_cpy_dllexport_python_decl(self, tp, name):
|
| 1291 |
+
self._extern_python_decl(tp, name, 'CFFI_DLLEXPORT ')
|
| 1292 |
+
|
| 1293 |
+
def _generate_cpy_extern_python_plus_c_decl(self, tp, name):
|
| 1294 |
+
self._extern_python_decl(tp, name, '')
|
| 1295 |
+
|
| 1296 |
+
def _generate_cpy_extern_python_ctx(self, tp, name):
|
| 1297 |
+
if self.target_is_python:
|
| 1298 |
+
raise VerificationError(
|
| 1299 |
+
"cannot use 'extern \"Python\"' in the ABI mode")
|
| 1300 |
+
if tp.ellipsis:
|
| 1301 |
+
raise NotImplementedError("a vararg function is extern \"Python\"")
|
| 1302 |
+
type_index = self._typesdict[tp]
|
| 1303 |
+
type_op = CffiOp(OP_EXTERN_PYTHON, type_index)
|
| 1304 |
+
self._lsts["global"].append(
|
| 1305 |
+
GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name))
|
| 1306 |
+
|
| 1307 |
+
_generate_cpy_dllexport_python_ctx = \
|
| 1308 |
+
_generate_cpy_extern_python_plus_c_ctx = \
|
| 1309 |
+
_generate_cpy_extern_python_ctx
|
| 1310 |
+
|
| 1311 |
+
def _print_string_literal_in_array(self, s):
|
| 1312 |
+
prnt = self._prnt
|
| 1313 |
+
prnt('// # NB. this is not a string because of a size limit in MSVC')
|
| 1314 |
+
if not isinstance(s, bytes): # unicode
|
| 1315 |
+
s = s.encode('utf-8') # -> bytes
|
| 1316 |
+
else:
|
| 1317 |
+
s.decode('utf-8') # got bytes, check for valid utf-8
|
| 1318 |
+
try:
|
| 1319 |
+
s.decode('ascii')
|
| 1320 |
+
except UnicodeDecodeError:
|
| 1321 |
+
s = b'# -*- encoding: utf8 -*-\n' + s
|
| 1322 |
+
for line in s.splitlines(True):
|
| 1323 |
+
comment = line
|
| 1324 |
+
if type('//') is bytes: # python2
|
| 1325 |
+
line = map(ord, line) # make a list of integers
|
| 1326 |
+
else: # python3
|
| 1327 |
+
# type(line) is bytes, which enumerates like a list of integers
|
| 1328 |
+
comment = ascii(comment)[1:-1]
|
| 1329 |
+
prnt(('// ' + comment).rstrip())
|
| 1330 |
+
printed_line = ''
|
| 1331 |
+
for c in line:
|
| 1332 |
+
if len(printed_line) >= 76:
|
| 1333 |
+
prnt(printed_line)
|
| 1334 |
+
printed_line = ''
|
| 1335 |
+
printed_line += '%d,' % (c,)
|
| 1336 |
+
prnt(printed_line)
|
| 1337 |
+
|
| 1338 |
+
# ----------
|
| 1339 |
+
# emitting the opcodes for individual types
|
| 1340 |
+
|
| 1341 |
+
def _emit_bytecode_VoidType(self, tp, index):
|
| 1342 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, PRIM_VOID)
|
| 1343 |
+
|
| 1344 |
+
def _emit_bytecode_PrimitiveType(self, tp, index):
|
| 1345 |
+
prim_index = PRIMITIVE_TO_INDEX[tp.name]
|
| 1346 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index)
|
| 1347 |
+
|
| 1348 |
+
def _emit_bytecode_UnknownIntegerType(self, tp, index):
|
| 1349 |
+
s = ('_cffi_prim_int(sizeof(%s), (\n'
|
| 1350 |
+
' ((%s)-1) | 0 /* check that %s is an integer type */\n'
|
| 1351 |
+
' ) <= 0)' % (tp.name, tp.name, tp.name))
|
| 1352 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
|
| 1353 |
+
|
| 1354 |
+
def _emit_bytecode_UnknownFloatType(self, tp, index):
|
| 1355 |
+
s = ('_cffi_prim_float(sizeof(%s) *\n'
|
| 1356 |
+
' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n'
|
| 1357 |
+
' )' % (tp.name, tp.name))
|
| 1358 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
|
| 1359 |
+
|
| 1360 |
+
def _emit_bytecode_RawFunctionType(self, tp, index):
|
| 1361 |
+
self.cffi_types[index] = CffiOp(OP_FUNCTION, self._typesdict[tp.result])
|
| 1362 |
+
index += 1
|
| 1363 |
+
for tp1 in tp.args:
|
| 1364 |
+
realindex = self._typesdict[tp1]
|
| 1365 |
+
if index != realindex:
|
| 1366 |
+
if isinstance(tp1, model.PrimitiveType):
|
| 1367 |
+
self._emit_bytecode_PrimitiveType(tp1, index)
|
| 1368 |
+
else:
|
| 1369 |
+
self.cffi_types[index] = CffiOp(OP_NOOP, realindex)
|
| 1370 |
+
index += 1
|
| 1371 |
+
flags = int(tp.ellipsis)
|
| 1372 |
+
if tp.abi is not None:
|
| 1373 |
+
if tp.abi == '__stdcall':
|
| 1374 |
+
flags |= 2
|
| 1375 |
+
else:
|
| 1376 |
+
raise NotImplementedError("abi=%r" % (tp.abi,))
|
| 1377 |
+
self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags)
|
| 1378 |
+
|
| 1379 |
+
def _emit_bytecode_PointerType(self, tp, index):
|
| 1380 |
+
self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[tp.totype])
|
| 1381 |
+
|
| 1382 |
+
_emit_bytecode_ConstPointerType = _emit_bytecode_PointerType
|
| 1383 |
+
_emit_bytecode_NamedPointerType = _emit_bytecode_PointerType
|
| 1384 |
+
|
| 1385 |
+
def _emit_bytecode_FunctionPtrType(self, tp, index):
|
| 1386 |
+
raw = tp.as_raw_function()
|
| 1387 |
+
self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[raw])
|
| 1388 |
+
|
| 1389 |
+
def _emit_bytecode_ArrayType(self, tp, index):
|
| 1390 |
+
item_index = self._typesdict[tp.item]
|
| 1391 |
+
if tp.length is None:
|
| 1392 |
+
self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index)
|
| 1393 |
+
elif tp.length == '...':
|
| 1394 |
+
raise VerificationError(
|
| 1395 |
+
"type %s badly placed: the '...' array length can only be "
|
| 1396 |
+
"used on global arrays or on fields of structures" % (
|
| 1397 |
+
str(tp).replace('/*...*/', '...'),))
|
| 1398 |
+
else:
|
| 1399 |
+
assert self.cffi_types[index + 1] == 'LEN'
|
| 1400 |
+
self.cffi_types[index] = CffiOp(OP_ARRAY, item_index)
|
| 1401 |
+
self.cffi_types[index + 1] = CffiOp(None, str(tp.length))
|
| 1402 |
+
|
| 1403 |
+
def _emit_bytecode_StructType(self, tp, index):
|
| 1404 |
+
struct_index = self._struct_unions[tp]
|
| 1405 |
+
self.cffi_types[index] = CffiOp(OP_STRUCT_UNION, struct_index)
|
| 1406 |
+
_emit_bytecode_UnionType = _emit_bytecode_StructType
|
| 1407 |
+
|
| 1408 |
+
def _emit_bytecode_EnumType(self, tp, index):
|
| 1409 |
+
enum_index = self._enums[tp]
|
| 1410 |
+
self.cffi_types[index] = CffiOp(OP_ENUM, enum_index)
|
| 1411 |
+
|
| 1412 |
+
|
| 1413 |
+
if sys.version_info >= (3,):
|
| 1414 |
+
NativeIO = io.StringIO
|
| 1415 |
+
else:
|
| 1416 |
+
class NativeIO(io.BytesIO):
|
| 1417 |
+
def write(self, s):
|
| 1418 |
+
if isinstance(s, unicode):
|
| 1419 |
+
s = s.encode('ascii')
|
| 1420 |
+
super(NativeIO, self).write(s)
|
| 1421 |
+
|
| 1422 |
+
def _is_file_like(maybefile):
|
| 1423 |
+
# compare to xml.etree.ElementTree._get_writer
|
| 1424 |
+
return hasattr(maybefile, 'write')
|
| 1425 |
+
|
| 1426 |
+
def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose):
|
| 1427 |
+
if verbose:
|
| 1428 |
+
print("generating %s" % (target_file,))
|
| 1429 |
+
recompiler = Recompiler(ffi, module_name,
|
| 1430 |
+
target_is_python=(preamble is None))
|
| 1431 |
+
recompiler.collect_type_table()
|
| 1432 |
+
recompiler.collect_step_tables()
|
| 1433 |
+
if _is_file_like(target_file):
|
| 1434 |
+
recompiler.write_source_to_f(target_file, preamble)
|
| 1435 |
+
return True
|
| 1436 |
+
f = NativeIO()
|
| 1437 |
+
recompiler.write_source_to_f(f, preamble)
|
| 1438 |
+
output = f.getvalue()
|
| 1439 |
+
try:
|
| 1440 |
+
with open(target_file, 'r') as f1:
|
| 1441 |
+
if f1.read(len(output) + 1) != output:
|
| 1442 |
+
raise IOError
|
| 1443 |
+
if verbose:
|
| 1444 |
+
print("(already up-to-date)")
|
| 1445 |
+
return False # already up-to-date
|
| 1446 |
+
except IOError:
|
| 1447 |
+
tmp_file = '%s.~%d' % (target_file, os.getpid())
|
| 1448 |
+
with open(tmp_file, 'w') as f1:
|
| 1449 |
+
f1.write(output)
|
| 1450 |
+
try:
|
| 1451 |
+
os.rename(tmp_file, target_file)
|
| 1452 |
+
except OSError:
|
| 1453 |
+
os.unlink(target_file)
|
| 1454 |
+
os.rename(tmp_file, target_file)
|
| 1455 |
+
return True
|
| 1456 |
+
|
| 1457 |
+
def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False):
|
| 1458 |
+
assert preamble is not None
|
| 1459 |
+
return _make_c_or_py_source(ffi, module_name, preamble, target_c_file,
|
| 1460 |
+
verbose)
|
| 1461 |
+
|
| 1462 |
+
def make_py_source(ffi, module_name, target_py_file, verbose=False):
|
| 1463 |
+
return _make_c_or_py_source(ffi, module_name, None, target_py_file,
|
| 1464 |
+
verbose)
|
| 1465 |
+
|
| 1466 |
+
def _modname_to_file(outputdir, modname, extension):
|
| 1467 |
+
parts = modname.split('.')
|
| 1468 |
+
try:
|
| 1469 |
+
os.makedirs(os.path.join(outputdir, *parts[:-1]))
|
| 1470 |
+
except OSError:
|
| 1471 |
+
pass
|
| 1472 |
+
parts[-1] += extension
|
| 1473 |
+
return os.path.join(outputdir, *parts), parts
|
| 1474 |
+
|
| 1475 |
+
|
| 1476 |
+
# Aaargh. Distutils is not tested at all for the purpose of compiling
|
| 1477 |
+
# DLLs that are not extension modules. Here are some hacks to work
|
| 1478 |
+
# around that, in the _patch_for_*() functions...
|
| 1479 |
+
|
| 1480 |
+
def _patch_meth(patchlist, cls, name, new_meth):
|
| 1481 |
+
old = getattr(cls, name)
|
| 1482 |
+
patchlist.append((cls, name, old))
|
| 1483 |
+
setattr(cls, name, new_meth)
|
| 1484 |
+
return old
|
| 1485 |
+
|
| 1486 |
+
def _unpatch_meths(patchlist):
|
| 1487 |
+
for cls, name, old_meth in reversed(patchlist):
|
| 1488 |
+
setattr(cls, name, old_meth)
|
| 1489 |
+
|
| 1490 |
+
def _patch_for_embedding(patchlist):
|
| 1491 |
+
if sys.platform == 'win32':
|
| 1492 |
+
# we must not remove the manifest when building for embedding!
|
| 1493 |
+
# FUTURE: this module was removed in setuptools 74; this is likely dead code and should be removed,
|
| 1494 |
+
# since the toolchain it supports (VS2005-2008) is also long dead.
|
| 1495 |
+
from cffi._shimmed_dist_utils import MSVCCompiler
|
| 1496 |
+
if MSVCCompiler is not None:
|
| 1497 |
+
_patch_meth(patchlist, MSVCCompiler, '_remove_visual_c_ref',
|
| 1498 |
+
lambda self, manifest_file: manifest_file)
|
| 1499 |
+
|
| 1500 |
+
if sys.platform == 'darwin':
|
| 1501 |
+
# we must not make a '-bundle', but a '-dynamiclib' instead
|
| 1502 |
+
from cffi._shimmed_dist_utils import CCompiler
|
| 1503 |
+
def my_link_shared_object(self, *args, **kwds):
|
| 1504 |
+
if '-bundle' in self.linker_so:
|
| 1505 |
+
self.linker_so = list(self.linker_so)
|
| 1506 |
+
i = self.linker_so.index('-bundle')
|
| 1507 |
+
self.linker_so[i] = '-dynamiclib'
|
| 1508 |
+
return old_link_shared_object(self, *args, **kwds)
|
| 1509 |
+
old_link_shared_object = _patch_meth(patchlist, CCompiler,
|
| 1510 |
+
'link_shared_object',
|
| 1511 |
+
my_link_shared_object)
|
| 1512 |
+
|
| 1513 |
+
def _patch_for_target(patchlist, target):
|
| 1514 |
+
from cffi._shimmed_dist_utils import build_ext
|
| 1515 |
+
# if 'target' is different from '*', we need to patch some internal
|
| 1516 |
+
# method to just return this 'target' value, instead of having it
|
| 1517 |
+
# built from module_name
|
| 1518 |
+
if target.endswith('.*'):
|
| 1519 |
+
target = target[:-2]
|
| 1520 |
+
if sys.platform == 'win32':
|
| 1521 |
+
target += '.dll'
|
| 1522 |
+
elif sys.platform == 'darwin':
|
| 1523 |
+
target += '.dylib'
|
| 1524 |
+
else:
|
| 1525 |
+
target += '.so'
|
| 1526 |
+
_patch_meth(patchlist, build_ext, 'get_ext_filename',
|
| 1527 |
+
lambda self, ext_name: target)
|
| 1528 |
+
|
| 1529 |
+
|
| 1530 |
+
def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True,
|
| 1531 |
+
c_file=None, source_extension='.c', extradir=None,
|
| 1532 |
+
compiler_verbose=1, target=None, debug=None,
|
| 1533 |
+
uses_ffiplatform=True, **kwds):
|
| 1534 |
+
if not isinstance(module_name, str):
|
| 1535 |
+
module_name = module_name.encode('ascii')
|
| 1536 |
+
if ffi._windows_unicode:
|
| 1537 |
+
ffi._apply_windows_unicode(kwds)
|
| 1538 |
+
if preamble is not None:
|
| 1539 |
+
if call_c_compiler and _is_file_like(c_file):
|
| 1540 |
+
raise TypeError("Writing to file-like objects is not supported "
|
| 1541 |
+
"with call_c_compiler=True")
|
| 1542 |
+
embedding = (ffi._embedding is not None)
|
| 1543 |
+
if embedding:
|
| 1544 |
+
ffi._apply_embedding_fix(kwds)
|
| 1545 |
+
if c_file is None:
|
| 1546 |
+
c_file, parts = _modname_to_file(tmpdir, module_name,
|
| 1547 |
+
source_extension)
|
| 1548 |
+
if extradir:
|
| 1549 |
+
parts = [extradir] + parts
|
| 1550 |
+
ext_c_file = os.path.join(*parts)
|
| 1551 |
+
else:
|
| 1552 |
+
ext_c_file = c_file
|
| 1553 |
+
#
|
| 1554 |
+
if target is None:
|
| 1555 |
+
if embedding:
|
| 1556 |
+
target = '%s.*' % module_name
|
| 1557 |
+
else:
|
| 1558 |
+
target = '*'
|
| 1559 |
+
#
|
| 1560 |
+
if uses_ffiplatform:
|
| 1561 |
+
ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds)
|
| 1562 |
+
else:
|
| 1563 |
+
ext = None
|
| 1564 |
+
updated = make_c_source(ffi, module_name, preamble, c_file,
|
| 1565 |
+
verbose=compiler_verbose)
|
| 1566 |
+
if call_c_compiler:
|
| 1567 |
+
patchlist = []
|
| 1568 |
+
cwd = os.getcwd()
|
| 1569 |
+
try:
|
| 1570 |
+
if embedding:
|
| 1571 |
+
_patch_for_embedding(patchlist)
|
| 1572 |
+
if target != '*':
|
| 1573 |
+
_patch_for_target(patchlist, target)
|
| 1574 |
+
if compiler_verbose:
|
| 1575 |
+
if tmpdir == '.':
|
| 1576 |
+
msg = 'the current directory is'
|
| 1577 |
+
else:
|
| 1578 |
+
msg = 'setting the current directory to'
|
| 1579 |
+
print('%s %r' % (msg, os.path.abspath(tmpdir)))
|
| 1580 |
+
os.chdir(tmpdir)
|
| 1581 |
+
outputfilename = ffiplatform.compile('.', ext,
|
| 1582 |
+
compiler_verbose, debug)
|
| 1583 |
+
finally:
|
| 1584 |
+
os.chdir(cwd)
|
| 1585 |
+
_unpatch_meths(patchlist)
|
| 1586 |
+
return outputfilename
|
| 1587 |
+
else:
|
| 1588 |
+
return ext, updated
|
| 1589 |
+
else:
|
| 1590 |
+
if c_file is None:
|
| 1591 |
+
c_file, _ = _modname_to_file(tmpdir, module_name, '.py')
|
| 1592 |
+
updated = make_py_source(ffi, module_name, c_file,
|
| 1593 |
+
verbose=compiler_verbose)
|
| 1594 |
+
if call_c_compiler:
|
| 1595 |
+
return c_file
|
| 1596 |
+
else:
|
| 1597 |
+
return None, updated
|
| 1598 |
+
|