| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
import sys |
| 5 |
import os.path |
| 6 |
import functools |
| 7 |
import re |
| 8 |
from pathlib import Path |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
import setuptools |
| 16 |
import distutils |
| 17 |
if (sys.version_info.major > 2 and |
| 18 |
distutils is not getattr(setuptools, '_distutils', None)): |
| 19 |
raise Exception( |
| 20 |
"setuptools' monkey-patching of distutils did not work. " |
| 21 |
"Most likely this is caused by:\n" |
| 22 |
" - a too old setuptools. Try installing setuptools>=60.2\n" |
| 23 |
" - the env variable SETUPTOOLS_USE_DISTUTILS=stdlib. Try to unset it." |
| 24 |
) |
| 25 |
from distutils import log |
| 26 |
from distutils.errors import DistutilsError |
| 27 |
import setuptools.command as cmd |
| 28 |
try: |
| 29 |
import setuptools.command.build |
| 30 |
except ImportError: |
| 31 |
print( |
| 32 |
"warning: setuptools.command.build does not exist in setuptools", |
| 33 |
setuptools.__version__, "on", sys.version |
| 34 |
) |
| 35 |
setuptools.command.build = None |
| 36 |
import setuptools.command.build_ext |
| 37 |
import setuptools.command.bdist_egg |
| 38 |
|
| 39 |
from .abitag import get_hpy_ext_suffix |
| 40 |
|
| 41 |
DEFAULT_HPY_ABI = 'universal' |
| 42 |
if hasattr(sys, 'implementation') and sys.implementation.name == 'cpython': |
| 43 |
DEFAULT_HPY_ABI = 'cpython' |
| 44 |
|
| 45 |
|
| 46 |
class HPyDevel: |
| 47 |
""" Extra sources for building HPy extensions with hpy.devel. """ |
| 48 |
|
| 49 |
_DEFAULT_BASE_DIR = Path(__file__).parent |
| 50 |
|
| 51 |
def __init__(self, base_dir=_DEFAULT_BASE_DIR): |
| 52 |
self.base_dir = Path(base_dir) |
| 53 |
self.include_dir = self.base_dir.joinpath('include') |
| 54 |
self.src_dir = self.base_dir.joinpath('src', 'runtime') |
| 55 |
self._available_static_libs = None |
| 56 |
|
| 57 |
def get_extra_include_dirs(self): |
| 58 |
""" Extra include directories needed by extensions in both CPython and |
| 59 |
Universal modes. |
| 60 |
""" |
| 61 |
return list(map(str, [ |
| 62 |
self.include_dir, |
| 63 |
])) |
| 64 |
|
| 65 |
def get_include_dir_forbid_python_h(self): |
| 66 |
return self.include_dir.joinpath('hpy', 'forbid_python_h') |
| 67 |
|
| 68 |
def get_extra_sources(self): |
| 69 |
""" Extra sources needed by extensions in both CPython and Universal |
| 70 |
modes. |
| 71 |
""" |
| 72 |
return list(map(str, [ |
| 73 |
self.src_dir.joinpath('argparse.c'), |
| 74 |
self.src_dir.joinpath('buildvalue.c'), |
| 75 |
self.src_dir.joinpath('format.c'), |
| 76 |
self.src_dir.joinpath('helpers.c'), |
| 77 |
self.src_dir.joinpath('structseq.c'), |
| 78 |
])) |
| 79 |
|
| 80 |
def _scan_static_lib_dir(self): |
| 81 |
""" Scan the static library directory and build a dict for all |
| 82 |
available static libraries. The library directory contains |
| 83 |
subdirectories for each ABI and the ABI folders then contain |
| 84 |
the static libraries. |
| 85 |
""" |
| 86 |
available_libs = {} |
| 87 |
lib_dir = self.base_dir.joinpath('lib') |
| 88 |
if lib_dir.exists(): |
| 89 |
for abi_dir in lib_dir.iterdir(): |
| 90 |
if abi_dir.is_dir(): |
| 91 |
abi = abi_dir.name |
| 92 |
|
| 93 |
|
| 94 |
available_libs[abi] = \ |
| 95 |
[str(x) for x in abi_dir.iterdir() if x.is_file()] |
| 96 |
return available_libs |
| 97 |
|
| 98 |
def get_static_libs(self, hpy_abi): |
| 99 |
""" The list of necessary static libraries an HPy extension needs to |
| 100 |
link to or 'None' (if not available). The HPy ext needs to link to |
| 101 |
all static libraries in the list otherwise some function may stay |
| 102 |
unresolved. For example, there is library 'hpyextra' which contains |
| 103 |
compiled HPy helper functions like 'HPyArg_Parse' and such. |
| 104 |
Libraries are always specific to an ABI. |
| 105 |
""" |
| 106 |
if not self._available_static_libs: |
| 107 |
|
| 108 |
self._available_static_libs = self._scan_static_lib_dir() |
| 109 |
return self._available_static_libs.get(hpy_abi, None) |
| 110 |
|
| 111 |
def get_ctx_sources(self): |
| 112 |
""" Extra sources needed only in the CPython ABI mode. |
| 113 |
""" |
| 114 |
return list(map(str, self.src_dir.glob('ctx_*.c'))) |
| 115 |
|
| 116 |
def fix_distribution(self, dist): |
| 117 |
""" Override build_ext to support hpy modules. |
| 118 |
|
| 119 |
Used from both setup.py and hpy/test. |
| 120 |
""" |
| 121 |
|
| 122 |
dist.hpydevel = self |
| 123 |
|
| 124 |
@monkeypatch(dist.__class__) |
| 125 |
def has_ext_modules(self): |
| 126 |
if self.ext_modules or self.hpy_ext_modules: |
| 127 |
return True |
| 128 |
return False |
| 129 |
|
| 130 |
|
| 131 |
if cmd.build is not None: |
| 132 |
build = dist.cmdclass.get("build", cmd.build.build) |
| 133 |
build_hpy = make_mixin(build, build_hpy_mixin) |
| 134 |
dist.cmdclass['build'] = build_hpy |
| 135 |
|
| 136 |
|
| 137 |
build_ext = dist.cmdclass.get("build_ext", cmd.build_ext.build_ext) |
| 138 |
self.build_ext_sanity_check(build_ext) |
| 139 |
build_ext_hpy = make_mixin(build_ext, build_ext_hpy_mixin) |
| 140 |
dist.cmdclass['build_ext'] = build_ext_hpy |
| 141 |
|
| 142 |
|
| 143 |
@monkeypatch(setuptools.command.bdist_egg) |
| 144 |
def write_stub(resource, pyfile): |
| 145 |
""" |
| 146 |
This is needed because the default bdist_egg unconditionally writes a .py |
| 147 |
stub, thus overwriting the one which was created by |
| 148 |
build_ext_hpy_mixin.write_stub. |
| 149 |
""" |
| 150 |
ext_suffix = None |
| 151 |
if dist.hpy_abi != 'cpython': |
| 152 |
ext_suffix = get_hpy_ext_suffix(dist.hpy_abi) |
| 153 |
|
| 154 |
if ext_suffix and resource.endswith(ext_suffix): |
| 155 |
log.info("stub file already created for %s", resource) |
| 156 |
else: |
| 157 |
write_stub.super(resource, pyfile) |
| 158 |
|
| 159 |
def build_ext_sanity_check(self, build_ext): |
| 160 |
|
| 161 |
if isinstance(build_ext, type): |
| 162 |
assert ('setuptools.command.build_ext', 'build_ext') in [ |
| 163 |
(c.__module__, c.__name__) for c in build_ext.__mro__ |
| 164 |
], ( |
| 165 |
"dist.cmdclass['build_ext'] does not inherit from" |
| 166 |
" setuptools.command.build_ext.build_ext. The HPy build" |
| 167 |
" system does not currently support any other build_ext" |
| 168 |
" classes. If you are using distutils.commands.build_ext," |
| 169 |
" please use setuptools.commands.build_ext instead." |
| 170 |
) |
| 171 |
|
| 172 |
|
| 173 |
def handle_hpy_ext_modules(dist, attr, hpy_ext_modules): |
| 174 |
""" Distuils hpy_ext_module setup(...) argument and --hpy-abi option. |
| 175 |
|
| 176 |
See hpy's setup.py where this function is registered as an entry |
| 177 |
point. |
| 178 |
""" |
| 179 |
assert attr == 'hpy_ext_modules' |
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
if getattr(dist, 'hpydevel', None): |
| 185 |
return |
| 186 |
|
| 187 |
|
| 188 |
dist.__class__.hpy_abi = DEFAULT_HPY_ABI |
| 189 |
dist.__class__.hpy_use_static_libs = False |
| 190 |
dist.__class__.global_options += [ |
| 191 |
('hpy-abi=', None, 'Specify the HPy ABI mode (default: %s)' |
| 192 |
% DEFAULT_HPY_ABI), |
| 193 |
('hpy-use-static-libs', None, 'Use static library containing context ' |
| 194 |
'and helper functions for building ' |
| 195 |
'extensions (default: False)') |
| 196 |
] |
| 197 |
hpydevel = HPyDevel() |
| 198 |
hpydevel.fix_distribution(dist) |
| 199 |
|
| 200 |
|
| 201 |
_HPY_UNIVERSAL_MODULE_STUB_TEMPLATE = """ |
| 202 |
# DO NOT EDIT THIS FILE! |
| 203 |
# This file is automatically generated by hpy |
| 204 |
|
| 205 |
def __bootstrap__(): |
| 206 |
|
| 207 |
from sys import modules |
| 208 |
from os import environ |
| 209 |
from pkg_resources import resource_filename |
| 210 |
from hpy.universal import _load_bootstrap |
| 211 |
ext_filepath = resource_filename(__name__, {ext_file!r}) |
| 212 |
m = _load_bootstrap({module_name!r}, __name__, __package__, ext_filepath, |
| 213 |
__loader__, __spec__, environ) |
| 214 |
modules[__name__] = m |
| 215 |
|
| 216 |
__bootstrap__() |
| 217 |
""" |
| 218 |
|
| 219 |
|
| 220 |
class HPyExtensionName(str): |
| 221 |
""" Wrapper around str to allow HPy extension modules to be identified. |
| 222 |
|
| 223 |
The following build_ext command methods are passed only the *name* |
| 224 |
of the extension and not the full extension object. The |
| 225 |
build_ext_hpy_mixin class needs to detect when HPy are extensions |
| 226 |
passed to these methods and override the default behaviour. |
| 227 |
|
| 228 |
This str sub-class allows HPy extensions to be detected, while |
| 229 |
still allowing the extension name to be used as an ordinary string. |
| 230 |
""" |
| 231 |
|
| 232 |
def split(self, *args, **kw): |
| 233 |
result = str.split(self, *args, **kw) |
| 234 |
return [self.__class__(s) for s in result] |
| 235 |
|
| 236 |
def translate(self, *args, **kw): |
| 237 |
result = str.translate(self, *args, **kw) |
| 238 |
return self.__class__(result) |
| 239 |
|
| 240 |
|
| 241 |
def is_hpy_extension(ext_name): |
| 242 |
""" Return True if the extension name is for an HPy extension. """ |
| 243 |
return isinstance(ext_name, HPyExtensionName) |
| 244 |
|
| 245 |
|
| 246 |
def remember_hpy_extension(f): |
| 247 |
""" Decorator for remembering whether an extension name belongs to an |
| 248 |
HPy extension. |
| 249 |
""" |
| 250 |
@functools.wraps(f) |
| 251 |
def wrapper(self, ext_name): |
| 252 |
if self._only_hpy_extensions: |
| 253 |
assert is_hpy_extension(ext_name), ( |
| 254 |
"Extension name %r is not marked as an HPyExtensionName" |
| 255 |
" but only HPy extensions are present. This is almost" |
| 256 |
" certainly a bug in HPy's overriding of setuptools" |
| 257 |
" build_ext. Please report this error the HPy maintainers." |
| 258 |
% (ext_name,) |
| 259 |
) |
| 260 |
result = f(self, ext_name) |
| 261 |
if is_hpy_extension(ext_name): |
| 262 |
result = HPyExtensionName(result) |
| 263 |
return result |
| 264 |
return wrapper |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
def make_mixin(base, mixin): |
| 272 |
""" |
| 273 |
Create a new class which inherits from both mixin and base, so that the |
| 274 |
methods of mixin effectively override the ones of base |
| 275 |
""" |
| 276 |
class NewClass(mixin, base, object): |
| 277 |
_mixin_super = base |
| 278 |
NewClass.__name__ = base.__name__ + '_hpy' |
| 279 |
return NewClass |
| 280 |
|
| 281 |
def monkeypatch(target): |
| 282 |
""" |
| 283 |
Decorator to monkey patch a function in a module. The original function |
| 284 |
will be available as new_function.super() |
| 285 |
""" |
| 286 |
def decorator(fn): |
| 287 |
name = fn.__name__ |
| 288 |
fn.super = getattr(target, name) |
| 289 |
setattr(target, name, fn) |
| 290 |
return fn |
| 291 |
return decorator |
| 292 |
|
| 293 |
|
| 294 |
class build_hpy_mixin: |
| 295 |
""" A mixin class to override setuptools.commands.build """ |
| 296 |
|
| 297 |
def finalize_options(self): |
| 298 |
self._mixin_super.finalize_options(self) |
| 299 |
if self.distribution.hpy_abi != 'cpython': |
| 300 |
suffix = '-hpy-%s' % self.distribution.hpy_abi |
| 301 |
self.build_platlib += suffix |
| 302 |
self.build_lib += suffix |
| 303 |
self.build_temp += suffix |
| 304 |
|
| 305 |
|
| 306 |
class build_ext_hpy_mixin: |
| 307 |
""" A mixin class to override setuptools.commands.build_ext """ |
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
_extensions = None |
| 317 |
|
| 318 |
@property |
| 319 |
def extensions(self): |
| 320 |
return self._extensions |
| 321 |
|
| 322 |
@extensions.setter |
| 323 |
def extensions(self, value): |
| 324 |
pass |
| 325 |
|
| 326 |
def initialize_options(self): |
| 327 |
self._mixin_super.initialize_options(self) |
| 328 |
self.hpydevel = self.distribution.hpydevel |
| 329 |
|
| 330 |
def _finalize_hpy_ext(self, ext): |
| 331 |
if hasattr(ext, "hpy_abi"): |
| 332 |
return |
| 333 |
ext.name = HPyExtensionName(ext.name) |
| 334 |
ext.hpy_abi = self.distribution.hpy_abi |
| 335 |
ext.include_dirs += self.hpydevel.get_extra_include_dirs() |
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
static_libs = self.distribution.hpy_use_static_libs |
| 340 |
if static_libs: |
| 341 |
static_libs = self.hpydevel.get_static_libs(ext.hpy_abi) |
| 342 |
if static_libs is None or len(static_libs) != 1: |
| 343 |
raise DistutilsError('Expected exactly one static library for ' |
| 344 |
'ABI "%s" but got: %r' % |
| 345 |
(ext.hpy_abi, static_libs)) |
| 346 |
|
| 347 |
if static_libs: |
| 348 |
ext.extra_objects += static_libs |
| 349 |
else: |
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
ext.sources += self.hpydevel.get_extra_sources() |
| 354 |
ext.define_macros.append(('HPY', None)) |
| 355 |
if ext.hpy_abi == 'cpython': |
| 356 |
|
| 357 |
|
| 358 |
if not static_libs: |
| 359 |
ext.sources += self.hpydevel.get_ctx_sources() |
| 360 |
ext.define_macros.append(('HPY_ABI_CPYTHON', None)) |
| 361 |
ext._hpy_needs_stub = False |
| 362 |
elif ext.hpy_abi == 'hybrid': |
| 363 |
ext.define_macros.append(('HPY_ABI_HYBRID', None)) |
| 364 |
ext._hpy_needs_stub = True |
| 365 |
elif ext.hpy_abi == 'universal': |
| 366 |
ext.define_macros.append(('HPY_ABI_UNIVERSAL', None)) |
| 367 |
ext._hpy_needs_stub = True |
| 368 |
forbid_python_h = self.hpydevel.get_include_dir_forbid_python_h() |
| 369 |
ext.include_dirs.insert(0, forbid_python_h) |
| 370 |
else: |
| 371 |
raise DistutilsError('Unknown HPy ABI: %s. Valid values are: ' |
| 372 |
'cpython, hybrid, universal' % ext.hpy_abi) |
| 373 |
|
| 374 |
def finalize_options(self): |
| 375 |
self._extensions = self.distribution.ext_modules or [] |
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
self._only_hpy_extensions = not bool(self._extensions) |
| 380 |
hpy_ext_modules = self.distribution.hpy_ext_modules or [] |
| 381 |
for ext in hpy_ext_modules: |
| 382 |
self._finalize_hpy_ext(ext) |
| 383 |
self._extensions.extend(hpy_ext_modules) |
| 384 |
self._mixin_super.finalize_options(self) |
| 385 |
for ext in hpy_ext_modules: |
| 386 |
ext._needs_stub = ext._hpy_needs_stub |
| 387 |
|
| 388 |
@remember_hpy_extension |
| 389 |
def get_ext_fullname(self, ext_name): |
| 390 |
return self._mixin_super.get_ext_fullname(self, ext_name) |
| 391 |
|
| 392 |
@remember_hpy_extension |
| 393 |
def get_ext_fullpath(self, ext_name): |
| 394 |
return self._mixin_super.get_ext_fullpath(self, ext_name) |
| 395 |
|
| 396 |
@remember_hpy_extension |
| 397 |
def get_ext_filename(self, ext_name): |
| 398 |
hpy_abi = self.distribution.hpy_abi |
| 399 |
if not is_hpy_extension(ext_name) or hpy_abi == 'cpython': |
| 400 |
return self._mixin_super.get_ext_filename(self, ext_name) |
| 401 |
else: |
| 402 |
assert is_hpy_extension(ext_name) |
| 403 |
assert hpy_abi in ('universal', 'hybrid') |
| 404 |
ext_path = ext_name.split('.') |
| 405 |
ext_suffix = get_hpy_ext_suffix(hpy_abi) |
| 406 |
ext_filename = os.path.join(*ext_path) + ext_suffix |
| 407 |
return ext_filename |
| 408 |
|
| 409 |
def write_stub(self, output_dir, ext, compile=False): |
| 410 |
if (not hasattr(ext, "hpy_abi") or |
| 411 |
self.distribution.hpy_abi not in ('universal', 'hybrid')): |
| 412 |
return self._mixin_super.write_stub( |
| 413 |
self, output_dir, ext, compile=compile) |
| 414 |
pkgs = ext._full_name.split('.') |
| 415 |
if compile: |
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
pkgs = [pkgs[-1]] |
| 423 |
stub_file = os.path.join(output_dir, *pkgs) + '.py' |
| 424 |
log.info( |
| 425 |
"writing hpy universal stub loader for %s to %s", |
| 426 |
ext._full_name, stub_file) |
| 427 |
|
| 428 |
ext_file = os.path.basename(ext._file_name) |
| 429 |
module_name = ext_file.split(".")[0] |
| 430 |
if not self.dry_run: |
| 431 |
with open(stub_file, 'w', encoding='utf-8') as f: |
| 432 |
f.write(_HPY_UNIVERSAL_MODULE_STUB_TEMPLATE.format( |
| 433 |
ext_file=ext_file, module_name=module_name) |
| 434 |
) |
| 435 |
|
| 436 |
def copy_extensions_to_source(self): |
| 437 |
"""Override from setuptools 64.0.0 to copy our stub instead of recreating it.""" |
| 438 |
build_py = self.get_finalized_command('build_py') |
| 439 |
build_lib = build_py.build_lib |
| 440 |
for ext in self.extensions: |
| 441 |
inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext) |
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
if os.path.exists(regular_file) or not ext.optional: |
| 447 |
self.copy_file(regular_file, inplace_file, level=self.verbose) |
| 448 |
|
| 449 |
if ext._needs_stub: |
| 450 |
source_stub = os.path.join(build_lib, *ext._full_name.split('.')) + '.py' |
| 451 |
inplace_stub = self._get_equivalent_stub(ext, inplace_file) |
| 452 |
self.copy_file(source_stub, inplace_stub, level=self.verbose) |
| 453 |
|
| 454 |
def get_export_symbols(self, ext): |
| 455 |
""" Override .get_export_symbols to replace "PyInit_<module_name>" |
| 456 |
with "HPyInit_<module_name>. |
| 457 |
|
| 458 |
Only relevant on Windows, where the .pyd file (DLL) must export the |
| 459 |
module "HPyInit_" function. |
| 460 |
""" |
| 461 |
exports = self._mixin_super.get_export_symbols(self, ext) |
| 462 |
if hasattr(ext, "hpy_abi") and ext.hpy_abi in ('universal', 'hybrid'): |
| 463 |
exports = [re.sub(r"^PyInit_", "HPyInit_", name) for name in exports] |
| 464 |
return exports |