Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/distutils/ccompiler.py
7757 views
import os1import re2import sys3import shlex4import time5import subprocess6from copy import copy7from distutils import ccompiler8from distutils.ccompiler import (9compiler_class, gen_lib_options, get_default_compiler, new_compiler,10CCompiler11)12from distutils.errors import (13DistutilsExecError, DistutilsModuleError, DistutilsPlatformError,14CompileError, UnknownFileError15)16from distutils.sysconfig import customize_compiler17from distutils.version import LooseVersion1819from numpy.distutils import log20from numpy.distutils.exec_command import (21filepath_from_subprocess_output, forward_bytes_to_stdout22)23from numpy.distutils.misc_util import cyg2win32, is_sequence, mingw32, \24get_num_build_jobs, \25_commandline_dep_string, \26sanitize_cxx_flags2728# globals for parallel build management29import threading3031_job_semaphore = None32_global_lock = threading.Lock()33_processing_files = set()343536def _needs_build(obj, cc_args, extra_postargs, pp_opts):37"""38Check if an objects needs to be rebuild based on its dependencies3940Parameters41----------42obj : str43object file4445Returns46-------47bool48"""49# defined in unixcompiler.py50dep_file = obj + '.d'51if not os.path.exists(dep_file):52return True5354# dep_file is a makefile containing 'object: dependencies'55# formatted like posix shell (spaces escaped, \ line continuations)56# the last line contains the compiler commandline arguments as some57# projects may compile an extension multiple times with different58# arguments59with open(dep_file, "r") as f:60lines = f.readlines()6162cmdline =_commandline_dep_string(cc_args, extra_postargs, pp_opts)63last_cmdline = lines[-1]64if last_cmdline != cmdline:65return True6667contents = ''.join(lines[:-1])68deps = [x for x in shlex.split(contents, posix=True)69if x != "\n" and not x.endswith(":")]7071try:72t_obj = os.stat(obj).st_mtime7374# check if any of the dependencies is newer than the object75# the dependencies includes the source used to create the object76for f in deps:77if os.stat(f).st_mtime > t_obj:78return True79except OSError:80# no object counts as newer (shouldn't happen if dep_file exists)81return True8283return False848586def replace_method(klass, method_name, func):87# Py3k does not have unbound method anymore, MethodType does not work88m = lambda self, *args, **kw: func(self, *args, **kw)89setattr(klass, method_name, m)909192######################################################################93## Method that subclasses may redefine. But don't call this method,94## it i private to CCompiler class and may return unexpected95## results if used elsewhere. So, you have been warned..9697def CCompiler_find_executables(self):98"""99Does nothing here, but is called by the get_version method and can be100overridden by subclasses. In particular it is redefined in the `FCompiler`101class where more documentation can be found.102103"""104pass105106107replace_method(CCompiler, 'find_executables', CCompiler_find_executables)108109110# Using customized CCompiler.spawn.111def CCompiler_spawn(self, cmd, display=None, env=None):112"""113Execute a command in a sub-process.114115Parameters116----------117cmd : str118The command to execute.119display : str or sequence of str, optional120The text to add to the log file kept by `numpy.distutils`.121If not given, `display` is equal to `cmd`.122env: a dictionary for environment variables, optional123124Returns125-------126None127128Raises129------130DistutilsExecError131If the command failed, i.e. the exit status was not 0.132133"""134env = env if env is not None else dict(os.environ)135if display is None:136display = cmd137if is_sequence(display):138display = ' '.join(list(display))139log.info(display)140try:141if self.verbose:142subprocess.check_output(cmd, env=env)143else:144subprocess.check_output(cmd, stderr=subprocess.STDOUT, env=env)145except subprocess.CalledProcessError as exc:146o = exc.output147s = exc.returncode148except OSError as e:149# OSError doesn't have the same hooks for the exception150# output, but exec_command() historically would use an151# empty string for EnvironmentError (base class for152# OSError)153# o = b''154# still that would make the end-user lost in translation!155o = f"\n\n{e}\n\n\n"156try:157o = o.encode(sys.stdout.encoding)158except AttributeError:159o = o.encode('utf8')160# status previously used by exec_command() for parent161# of OSError162s = 127163else:164# use a convenience return here so that any kind of165# caught exception will execute the default code after the166# try / except block, which handles various exceptions167return None168169if is_sequence(cmd):170cmd = ' '.join(list(cmd))171172if self.verbose:173forward_bytes_to_stdout(o)174175if re.search(b'Too many open files', o):176msg = '\nTry rerunning setup command until build succeeds.'177else:178msg = ''179raise DistutilsExecError('Command "%s" failed with exit status %d%s' %180(cmd, s, msg))181182replace_method(CCompiler, 'spawn', CCompiler_spawn)183184def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''):185"""186Return the name of the object files for the given source files.187188Parameters189----------190source_filenames : list of str191The list of paths to source files. Paths can be either relative or192absolute, this is handled transparently.193strip_dir : bool, optional194Whether to strip the directory from the returned paths. If True,195the file name prepended by `output_dir` is returned. Default is False.196output_dir : str, optional197If given, this path is prepended to the returned paths to the198object files.199200Returns201-------202obj_names : list of str203The list of paths to the object files corresponding to the source204files in `source_filenames`.205206"""207if output_dir is None:208output_dir = ''209obj_names = []210for src_name in source_filenames:211base, ext = os.path.splitext(os.path.normpath(src_name))212base = os.path.splitdrive(base)[1] # Chop off the drive213base = base[os.path.isabs(base):] # If abs, chop off leading /214if base.startswith('..'):215# Resolve starting relative path components, middle ones216# (if any) have been handled by os.path.normpath above.217i = base.rfind('..')+2218d = base[:i]219d = os.path.basename(os.path.abspath(d))220base = d + base[i:]221if ext not in self.src_extensions:222raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name))223if strip_dir:224base = os.path.basename(base)225obj_name = os.path.join(output_dir, base + self.obj_extension)226obj_names.append(obj_name)227return obj_names228229replace_method(CCompiler, 'object_filenames', CCompiler_object_filenames)230231def CCompiler_compile(self, sources, output_dir=None, macros=None,232include_dirs=None, debug=0, extra_preargs=None,233extra_postargs=None, depends=None):234"""235Compile one or more source files.236237Please refer to the Python distutils API reference for more details.238239Parameters240----------241sources : list of str242A list of filenames243output_dir : str, optional244Path to the output directory.245macros : list of tuples246A list of macro definitions.247include_dirs : list of str, optional248The directories to add to the default include file search path for249this compilation only.250debug : bool, optional251Whether or not to output debug symbols in or alongside the object252file(s).253extra_preargs, extra_postargs : ?254Extra pre- and post-arguments.255depends : list of str, optional256A list of file names that all targets depend on.257258Returns259-------260objects : list of str261A list of object file names, one per source file `sources`.262263Raises264------265CompileError266If compilation fails.267268"""269global _job_semaphore270271jobs = get_num_build_jobs()272273# setup semaphore to not exceed number of compile jobs when parallelized at274# extension level (python >= 3.5)275with _global_lock:276if _job_semaphore is None:277_job_semaphore = threading.Semaphore(jobs)278279if not sources:280return []281from numpy.distutils.fcompiler import (FCompiler, is_f_file,282has_f90_header)283if isinstance(self, FCompiler):284display = []285for fc in ['f77', 'f90', 'fix']:286fcomp = getattr(self, 'compiler_'+fc)287if fcomp is None:288continue289display.append("Fortran %s compiler: %s" % (fc, ' '.join(fcomp)))290display = '\n'.join(display)291else:292ccomp = self.compiler_so293display = "C compiler: %s\n" % (' '.join(ccomp),)294log.info(display)295macros, objects, extra_postargs, pp_opts, build = \296self._setup_compile(output_dir, macros, include_dirs, sources,297depends, extra_postargs)298cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)299display = "compile options: '%s'" % (' '.join(cc_args))300if extra_postargs:301display += "\nextra options: '%s'" % (' '.join(extra_postargs))302log.info(display)303304def single_compile(args):305obj, (src, ext) = args306if not _needs_build(obj, cc_args, extra_postargs, pp_opts):307return308309# check if we are currently already processing the same object310# happens when using the same source in multiple extensions311while True:312# need explicit lock as there is no atomic check and add with GIL313with _global_lock:314# file not being worked on, start working315if obj not in _processing_files:316_processing_files.add(obj)317break318# wait for the processing to end319time.sleep(0.1)320321try:322# retrieve slot from our #job semaphore and build323with _job_semaphore:324self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)325finally:326# register being done processing327with _global_lock:328_processing_files.remove(obj)329330331if isinstance(self, FCompiler):332objects_to_build = list(build.keys())333f77_objects, other_objects = [], []334for obj in objects:335if obj in objects_to_build:336src, ext = build[obj]337if self.compiler_type=='absoft':338obj = cyg2win32(obj)339src = cyg2win32(src)340if is_f_file(src) and not has_f90_header(src):341f77_objects.append((obj, (src, ext)))342else:343other_objects.append((obj, (src, ext)))344345# f77 objects can be built in parallel346build_items = f77_objects347# build f90 modules serial, module files are generated during348# compilation and may be used by files later in the list so the349# ordering is important350for o in other_objects:351single_compile(o)352else:353build_items = build.items()354355if len(build) > 1 and jobs > 1:356# build parallel357from concurrent.futures import ThreadPoolExecutor358with ThreadPoolExecutor(jobs) as pool:359pool.map(single_compile, build_items)360else:361# build serial362for o in build_items:363single_compile(o)364365# Return *all* object filenames, not just the ones we just built.366return objects367368replace_method(CCompiler, 'compile', CCompiler_compile)369370def CCompiler_customize_cmd(self, cmd, ignore=()):371"""372Customize compiler using distutils command.373374Parameters375----------376cmd : class instance377An instance inheriting from `distutils.cmd.Command`.378ignore : sequence of str, optional379List of `CCompiler` commands (without ``'set_'``) that should not be380altered. Strings that are checked for are:381``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs',382'rpath', 'link_objects')``.383384Returns385-------386None387388"""389log.info('customize %s using %s' % (self.__class__.__name__,390cmd.__class__.__name__))391392if hasattr(self, 'compiler') and 'clang' in self.compiler[0]:393# clang defaults to a non-strict floating error point model.394# Since NumPy and most Python libs give warnings for these, override:395self.compiler.append('-ftrapping-math')396self.compiler_so.append('-ftrapping-math')397398def allow(attr):399return getattr(cmd, attr, None) is not None and attr not in ignore400401if allow('include_dirs'):402self.set_include_dirs(cmd.include_dirs)403if allow('define'):404for (name, value) in cmd.define:405self.define_macro(name, value)406if allow('undef'):407for macro in cmd.undef:408self.undefine_macro(macro)409if allow('libraries'):410self.set_libraries(self.libraries + cmd.libraries)411if allow('library_dirs'):412self.set_library_dirs(self.library_dirs + cmd.library_dirs)413if allow('rpath'):414self.set_runtime_library_dirs(cmd.rpath)415if allow('link_objects'):416self.set_link_objects(cmd.link_objects)417418replace_method(CCompiler, 'customize_cmd', CCompiler_customize_cmd)419420def _compiler_to_string(compiler):421props = []422mx = 0423keys = list(compiler.executables.keys())424for key in ['version', 'libraries', 'library_dirs',425'object_switch', 'compile_switch',426'include_dirs', 'define', 'undef', 'rpath', 'link_objects']:427if key not in keys:428keys.append(key)429for key in keys:430if hasattr(compiler, key):431v = getattr(compiler, key)432mx = max(mx, len(key))433props.append((key, repr(v)))434fmt = '%-' + repr(mx+1) + 's = %s'435lines = [fmt % prop for prop in props]436return '\n'.join(lines)437438def CCompiler_show_customization(self):439"""440Print the compiler customizations to stdout.441442Parameters443----------444None445446Returns447-------448None449450Notes451-----452Printing is only done if the distutils log threshold is < 2.453454"""455try:456self.get_version()457except Exception:458pass459if log._global_log.threshold<2:460print('*'*80)461print(self.__class__)462print(_compiler_to_string(self))463print('*'*80)464465replace_method(CCompiler, 'show_customization', CCompiler_show_customization)466467def CCompiler_customize(self, dist, need_cxx=0):468"""469Do any platform-specific customization of a compiler instance.470471This method calls `distutils.sysconfig.customize_compiler` for472platform-specific customization, as well as optionally remove a flag473to suppress spurious warnings in case C++ code is being compiled.474475Parameters476----------477dist : object478This parameter is not used for anything.479need_cxx : bool, optional480Whether or not C++ has to be compiled. If so (True), the481``"-Wstrict-prototypes"`` option is removed to prevent spurious482warnings. Default is False.483484Returns485-------486None487488Notes489-----490All the default options used by distutils can be extracted with::491492from distutils import sysconfig493sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',494'CCSHARED', 'LDSHARED', 'SO')495496"""497# See FCompiler.customize for suggested usage.498log.info('customize %s' % (self.__class__.__name__))499customize_compiler(self)500if need_cxx:501# In general, distutils uses -Wstrict-prototypes, but this option is502# not valid for C++ code, only for C. Remove it if it's there to503# avoid a spurious warning on every compilation.504try:505self.compiler_so.remove('-Wstrict-prototypes')506except (AttributeError, ValueError):507pass508509if hasattr(self, 'compiler') and 'cc' in self.compiler[0]:510if not self.compiler_cxx:511if self.compiler[0].startswith('gcc'):512a, b = 'gcc', 'g++'513else:514a, b = 'cc', 'c++'515self.compiler_cxx = [self.compiler[0].replace(a, b)]\516+ self.compiler[1:]517else:518if hasattr(self, 'compiler'):519log.warn("#### %s #######" % (self.compiler,))520if not hasattr(self, 'compiler_cxx'):521log.warn('Missing compiler_cxx fix for ' + self.__class__.__name__)522523524# check if compiler supports gcc style automatic dependencies525# run on every extension so skip for known good compilers526if hasattr(self, 'compiler') and ('gcc' in self.compiler[0] or527'g++' in self.compiler[0] or528'clang' in self.compiler[0]):529self._auto_depends = True530elif os.name == 'posix':531import tempfile532import shutil533tmpdir = tempfile.mkdtemp()534try:535fn = os.path.join(tmpdir, "file.c")536with open(fn, "w") as f:537f.write("int a;\n")538self.compile([fn], output_dir=tmpdir,539extra_preargs=['-MMD', '-MF', fn + '.d'])540self._auto_depends = True541except CompileError:542self._auto_depends = False543finally:544shutil.rmtree(tmpdir)545546return547548replace_method(CCompiler, 'customize', CCompiler_customize)549550def simple_version_match(pat=r'[-.\d]+', ignore='', start=''):551"""552Simple matching of version numbers, for use in CCompiler and FCompiler.553554Parameters555----------556pat : str, optional557A regular expression matching version numbers.558Default is ``r'[-.\\d]+'``.559ignore : str, optional560A regular expression matching patterns to skip.561Default is ``''``, in which case nothing is skipped.562start : str, optional563A regular expression matching the start of where to start looking564for version numbers.565Default is ``''``, in which case searching is started at the566beginning of the version string given to `matcher`.567568Returns569-------570matcher : callable571A function that is appropriate to use as the ``.version_match``572attribute of a `CCompiler` class. `matcher` takes a single parameter,573a version string.574575"""576def matcher(self, version_string):577# version string may appear in the second line, so getting rid578# of new lines:579version_string = version_string.replace('\n', ' ')580pos = 0581if start:582m = re.match(start, version_string)583if not m:584return None585pos = m.end()586while True:587m = re.search(pat, version_string[pos:])588if not m:589return None590if ignore and re.match(ignore, m.group(0)):591pos = m.end()592continue593break594return m.group(0)595return matcher596597def CCompiler_get_version(self, force=False, ok_status=[0]):598"""599Return compiler version, or None if compiler is not available.600601Parameters602----------603force : bool, optional604If True, force a new determination of the version, even if the605compiler already has a version attribute. Default is False.606ok_status : list of int, optional607The list of status values returned by the version look-up process608for which a version string is returned. If the status value is not609in `ok_status`, None is returned. Default is ``[0]``.610611Returns612-------613version : str or None614Version string, in the format of `distutils.version.LooseVersion`.615616"""617if not force and hasattr(self, 'version'):618return self.version619self.find_executables()620try:621version_cmd = self.version_cmd622except AttributeError:623return None624if not version_cmd or not version_cmd[0]:625return None626try:627matcher = self.version_match628except AttributeError:629try:630pat = self.version_pattern631except AttributeError:632return None633def matcher(version_string):634m = re.match(pat, version_string)635if not m:636return None637version = m.group('version')638return version639640try:641output = subprocess.check_output(version_cmd, stderr=subprocess.STDOUT)642except subprocess.CalledProcessError as exc:643output = exc.output644status = exc.returncode645except OSError:646# match the historical returns for a parent647# exception class caught by exec_command()648status = 127649output = b''650else:651# output isn't actually a filepath but we do this652# for now to match previous distutils behavior653output = filepath_from_subprocess_output(output)654status = 0655656version = None657if status in ok_status:658version = matcher(output)659if version:660version = LooseVersion(version)661self.version = version662return version663664replace_method(CCompiler, 'get_version', CCompiler_get_version)665666def CCompiler_cxx_compiler(self):667"""668Return the C++ compiler.669670Parameters671----------672None673674Returns675-------676cxx : class instance677The C++ compiler, as a `CCompiler` instance.678679"""680if self.compiler_type in ('msvc', 'intelw', 'intelemw'):681return self682683cxx = copy(self)684cxx.compiler_cxx = cxx.compiler_cxx685cxx.compiler_so = [cxx.compiler_cxx[0]] + \686sanitize_cxx_flags(cxx.compiler_so[1:])687if sys.platform.startswith('aix') and 'ld_so_aix' in cxx.linker_so[0]:688# AIX needs the ld_so_aix script included with Python689cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] \690+ cxx.linker_so[2:]691else:692cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:]693return cxx694695replace_method(CCompiler, 'cxx_compiler', CCompiler_cxx_compiler)696697compiler_class['intel'] = ('intelccompiler', 'IntelCCompiler',698"Intel C Compiler for 32-bit applications")699compiler_class['intele'] = ('intelccompiler', 'IntelItaniumCCompiler',700"Intel C Itanium Compiler for Itanium-based applications")701compiler_class['intelem'] = ('intelccompiler', 'IntelEM64TCCompiler',702"Intel C Compiler for 64-bit applications")703compiler_class['intelw'] = ('intelccompiler', 'IntelCCompilerW',704"Intel C Compiler for 32-bit applications on Windows")705compiler_class['intelemw'] = ('intelccompiler', 'IntelEM64TCCompilerW',706"Intel C Compiler for 64-bit applications on Windows")707compiler_class['pathcc'] = ('pathccompiler', 'PathScaleCCompiler',708"PathScale Compiler for SiCortex-based applications")709compiler_class['arm'] = ('armccompiler', 'ArmCCompiler',710"Arm C Compiler")711712ccompiler._default_compilers += (('linux.*', 'intel'),713('linux.*', 'intele'),714('linux.*', 'intelem'),715('linux.*', 'pathcc'),716('nt', 'intelw'),717('nt', 'intelemw'))718719if sys.platform == 'win32':720compiler_class['mingw32'] = ('mingw32ccompiler', 'Mingw32CCompiler',721"Mingw32 port of GNU C Compiler for Win32"\722"(for MSC built Python)")723if mingw32():724# On windows platforms, we want to default to mingw32 (gcc)725# because msvc can't build blitz stuff.726log.info('Setting mingw32 as default compiler for nt.')727ccompiler._default_compilers = (('nt', 'mingw32'),) \728+ ccompiler._default_compilers729730731_distutils_new_compiler = new_compiler732def new_compiler (plat=None,733compiler=None,734verbose=None,735dry_run=0,736force=0):737# Try first C compilers from numpy.distutils.738if verbose is None:739verbose = log.get_threshold() <= log.INFO740if plat is None:741plat = os.name742try:743if compiler is None:744compiler = get_default_compiler(plat)745(module_name, class_name, long_description) = compiler_class[compiler]746except KeyError:747msg = "don't know how to compile C/C++ code on platform '%s'" % plat748if compiler is not None:749msg = msg + " with '%s' compiler" % compiler750raise DistutilsPlatformError(msg)751module_name = "numpy.distutils." + module_name752try:753__import__ (module_name)754except ImportError as e:755msg = str(e)756log.info('%s in numpy.distutils; trying from distutils',757str(msg))758module_name = module_name[6:]759try:760__import__(module_name)761except ImportError as e:762msg = str(e)763raise DistutilsModuleError("can't compile C/C++ code: unable to load module '%s'" % \764module_name)765try:766module = sys.modules[module_name]767klass = vars(module)[class_name]768except KeyError:769raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " +770"in module '%s'") % (class_name, module_name))771compiler = klass(None, dry_run, force)772compiler.verbose = verbose773log.debug('new_compiler returns %s' % (klass))774return compiler775776ccompiler.new_compiler = new_compiler777778_distutils_gen_lib_options = gen_lib_options779def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):780# the version of this function provided by CPython allows the following781# to return lists, which are unpacked automatically:782# - compiler.runtime_library_dir_option783# our version extends the behavior to:784# - compiler.library_dir_option785# - compiler.library_option786# - compiler.find_library_file787r = _distutils_gen_lib_options(compiler, library_dirs,788runtime_library_dirs, libraries)789lib_opts = []790for i in r:791if is_sequence(i):792lib_opts.extend(list(i))793else:794lib_opts.append(i)795return lib_opts796ccompiler.gen_lib_options = gen_lib_options797798# Also fix up the various compiler modules, which do799# from distutils.ccompiler import gen_lib_options800# Don't bother with mwerks, as we don't support Classic Mac.801for _cc in ['msvc9', 'msvc', '_msvc', 'bcpp', 'cygwinc', 'emxc', 'unixc']:802_m = sys.modules.get('distutils.' + _cc + 'compiler')803if _m is not None:804setattr(_m, 'gen_lib_options', gen_lib_options)805806807808