You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

512 lines
15 KiB

4 years ago
  1. #
  2. # Cython -- Things that don't belong
  3. # anywhere else in particular
  4. #
  5. from __future__ import absolute_import
  6. try:
  7. from __builtin__ import basestring
  8. except ImportError:
  9. basestring = str
  10. try:
  11. FileNotFoundError
  12. except NameError:
  13. FileNotFoundError = OSError
  14. import os
  15. import sys
  16. import re
  17. import io
  18. import codecs
  19. import shutil
  20. from contextlib import contextmanager
  21. modification_time = os.path.getmtime
  22. _function_caches = []
  23. def clear_function_caches():
  24. for cache in _function_caches:
  25. cache.clear()
  26. def cached_function(f):
  27. cache = {}
  28. _function_caches.append(cache)
  29. uncomputed = object()
  30. def wrapper(*args):
  31. res = cache.get(args, uncomputed)
  32. if res is uncomputed:
  33. res = cache[args] = f(*args)
  34. return res
  35. wrapper.uncached = f
  36. return wrapper
  37. def cached_method(f):
  38. cache_name = '__%s_cache' % f.__name__
  39. def wrapper(self, *args):
  40. cache = getattr(self, cache_name, None)
  41. if cache is None:
  42. cache = {}
  43. setattr(self, cache_name, cache)
  44. if args in cache:
  45. return cache[args]
  46. res = cache[args] = f(self, *args)
  47. return res
  48. return wrapper
  49. def replace_suffix(path, newsuf):
  50. base, _ = os.path.splitext(path)
  51. return base + newsuf
  52. def open_new_file(path):
  53. if os.path.exists(path):
  54. # Make sure to create a new file here so we can
  55. # safely hard link the output files.
  56. os.unlink(path)
  57. # we use the ISO-8859-1 encoding here because we only write pure
  58. # ASCII strings or (e.g. for file names) byte encoded strings as
  59. # Unicode, so we need a direct mapping from the first 256 Unicode
  60. # characters to a byte sequence, which ISO-8859-1 provides
  61. # note: can't use io.open() in Py2 as we may be writing str objects
  62. return codecs.open(path, "w", encoding="ISO-8859-1")
  63. def castrate_file(path, st):
  64. # Remove junk contents from an output file after a
  65. # failed compilation.
  66. # Also sets access and modification times back to
  67. # those specified by st (a stat struct).
  68. try:
  69. f = open_new_file(path)
  70. except EnvironmentError:
  71. pass
  72. else:
  73. f.write(
  74. "#error Do not use this file, it is the result of a failed Cython compilation.\n")
  75. f.close()
  76. if st:
  77. os.utime(path, (st.st_atime, st.st_mtime-1))
  78. def file_newer_than(path, time):
  79. ftime = modification_time(path)
  80. return ftime > time
  81. def safe_makedirs(path):
  82. try:
  83. os.makedirs(path)
  84. except OSError:
  85. if not os.path.isdir(path):
  86. raise
  87. def copy_file_to_dir_if_newer(sourcefile, destdir):
  88. """
  89. Copy file sourcefile to directory destdir (creating it if needed),
  90. preserving metadata. If the destination file exists and is not
  91. older than the source file, the copying is skipped.
  92. """
  93. destfile = os.path.join(destdir, os.path.basename(sourcefile))
  94. try:
  95. desttime = modification_time(destfile)
  96. except OSError:
  97. # New file does not exist, destdir may or may not exist
  98. safe_makedirs(destdir)
  99. else:
  100. # New file already exists
  101. if not file_newer_than(sourcefile, desttime):
  102. return
  103. shutil.copy2(sourcefile, destfile)
  104. @cached_function
  105. def search_include_directories(dirs, qualified_name, suffix, pos,
  106. include=False, sys_path=False):
  107. # Search the list of include directories for the given
  108. # file name. If a source file position is given, first
  109. # searches the directory containing that file. Returns
  110. # None if not found, but does not report an error.
  111. # The 'include' option will disable package dereferencing.
  112. # If 'sys_path' is True, also search sys.path.
  113. if sys_path:
  114. dirs = dirs + tuple(sys.path)
  115. if pos:
  116. file_desc = pos[0]
  117. from Cython.Compiler.Scanning import FileSourceDescriptor
  118. if not isinstance(file_desc, FileSourceDescriptor):
  119. raise RuntimeError("Only file sources for code supported")
  120. if include:
  121. dirs = (os.path.dirname(file_desc.filename),) + dirs
  122. else:
  123. dirs = (find_root_package_dir(file_desc.filename),) + dirs
  124. dotted_filename = qualified_name
  125. if suffix:
  126. dotted_filename += suffix
  127. if not include:
  128. names = qualified_name.split('.')
  129. package_names = tuple(names[:-1])
  130. module_name = names[-1]
  131. module_filename = module_name + suffix
  132. package_filename = "__init__" + suffix
  133. for dir in dirs:
  134. path = os.path.join(dir, dotted_filename)
  135. if path_exists(path):
  136. return path
  137. if not include:
  138. package_dir = check_package_dir(dir, package_names)
  139. if package_dir is not None:
  140. path = os.path.join(package_dir, module_filename)
  141. if path_exists(path):
  142. return path
  143. path = os.path.join(dir, package_dir, module_name,
  144. package_filename)
  145. if path_exists(path):
  146. return path
  147. return None
  148. @cached_function
  149. def find_root_package_dir(file_path):
  150. dir = os.path.dirname(file_path)
  151. if file_path == dir:
  152. return dir
  153. elif is_package_dir(dir):
  154. return find_root_package_dir(dir)
  155. else:
  156. return dir
  157. @cached_function
  158. def check_package_dir(dir, package_names):
  159. for dirname in package_names:
  160. dir = os.path.join(dir, dirname)
  161. if not is_package_dir(dir):
  162. return None
  163. return dir
  164. @cached_function
  165. def is_package_dir(dir_path):
  166. for filename in ("__init__.py",
  167. "__init__.pyc",
  168. "__init__.pyx",
  169. "__init__.pxd"):
  170. path = os.path.join(dir_path, filename)
  171. if path_exists(path):
  172. return 1
  173. @cached_function
  174. def path_exists(path):
  175. # try on the filesystem first
  176. if os.path.exists(path):
  177. return True
  178. # figure out if a PEP 302 loader is around
  179. try:
  180. loader = __loader__
  181. # XXX the code below assumes a 'zipimport.zipimporter' instance
  182. # XXX should be easy to generalize, but too lazy right now to write it
  183. archive_path = getattr(loader, 'archive', None)
  184. if archive_path:
  185. normpath = os.path.normpath(path)
  186. if normpath.startswith(archive_path):
  187. arcname = normpath[len(archive_path)+1:]
  188. try:
  189. loader.get_data(arcname)
  190. return True
  191. except IOError:
  192. return False
  193. except NameError:
  194. pass
  195. return False
  196. # file name encodings
  197. def decode_filename(filename):
  198. if isinstance(filename, bytes):
  199. try:
  200. filename_encoding = sys.getfilesystemencoding()
  201. if filename_encoding is None:
  202. filename_encoding = sys.getdefaultencoding()
  203. filename = filename.decode(filename_encoding)
  204. except UnicodeDecodeError:
  205. pass
  206. return filename
  207. # support for source file encoding detection
  208. _match_file_encoding = re.compile(br"(\w*coding)[:=]\s*([-\w.]+)").search
  209. def detect_opened_file_encoding(f):
  210. # PEPs 263 and 3120
  211. # Most of the time the first two lines fall in the first couple of hundred chars,
  212. # and this bulk read/split is much faster.
  213. lines = ()
  214. start = b''
  215. while len(lines) < 3:
  216. data = f.read(500)
  217. start += data
  218. lines = start.split(b"\n")
  219. if not data:
  220. break
  221. m = _match_file_encoding(lines[0])
  222. if m and m.group(1) != b'c_string_encoding':
  223. return m.group(2).decode('iso8859-1')
  224. elif len(lines) > 1:
  225. m = _match_file_encoding(lines[1])
  226. if m:
  227. return m.group(2).decode('iso8859-1')
  228. return "UTF-8"
  229. def skip_bom(f):
  230. """
  231. Read past a BOM at the beginning of a source file.
  232. This could be added to the scanner, but it's *substantially* easier
  233. to keep it at this level.
  234. """
  235. if f.read(1) != u'\uFEFF':
  236. f.seek(0)
  237. def open_source_file(source_filename, encoding=None, error_handling=None):
  238. stream = None
  239. try:
  240. if encoding is None:
  241. # Most of the time the encoding is not specified, so try hard to open the file only once.
  242. f = io.open(source_filename, 'rb')
  243. encoding = detect_opened_file_encoding(f)
  244. f.seek(0)
  245. stream = io.TextIOWrapper(f, encoding=encoding, errors=error_handling)
  246. else:
  247. stream = io.open(source_filename, encoding=encoding, errors=error_handling)
  248. except OSError:
  249. if os.path.exists(source_filename):
  250. raise # File is there, but something went wrong reading from it.
  251. # Allow source files to be in zip files etc.
  252. try:
  253. loader = __loader__
  254. if source_filename.startswith(loader.archive):
  255. stream = open_source_from_loader(
  256. loader, source_filename,
  257. encoding, error_handling)
  258. except (NameError, AttributeError):
  259. pass
  260. if stream is None:
  261. raise FileNotFoundError(source_filename)
  262. skip_bom(stream)
  263. return stream
  264. def open_source_from_loader(loader,
  265. source_filename,
  266. encoding=None, error_handling=None):
  267. nrmpath = os.path.normpath(source_filename)
  268. arcname = nrmpath[len(loader.archive)+1:]
  269. data = loader.get_data(arcname)
  270. return io.TextIOWrapper(io.BytesIO(data),
  271. encoding=encoding,
  272. errors=error_handling)
  273. def str_to_number(value):
  274. # note: this expects a string as input that was accepted by the
  275. # parser already, with an optional "-" sign in front
  276. is_neg = False
  277. if value[:1] == '-':
  278. is_neg = True
  279. value = value[1:]
  280. if len(value) < 2:
  281. value = int(value, 0)
  282. elif value[0] == '0':
  283. literal_type = value[1] # 0'o' - 0'b' - 0'x'
  284. if literal_type in 'xX':
  285. # hex notation ('0x1AF')
  286. value = int(value[2:], 16)
  287. elif literal_type in 'oO':
  288. # Py3 octal notation ('0o136')
  289. value = int(value[2:], 8)
  290. elif literal_type in 'bB':
  291. # Py3 binary notation ('0b101')
  292. value = int(value[2:], 2)
  293. else:
  294. # Py2 octal notation ('0136')
  295. value = int(value, 8)
  296. else:
  297. value = int(value, 0)
  298. return -value if is_neg else value
  299. def long_literal(value):
  300. if isinstance(value, basestring):
  301. value = str_to_number(value)
  302. return not -2**31 <= value < 2**31
  303. @cached_function
  304. def get_cython_cache_dir():
  305. r"""
  306. Return the base directory containing Cython's caches.
  307. Priority:
  308. 1. CYTHON_CACHE_DIR
  309. 2. (OS X): ~/Library/Caches/Cython
  310. (posix not OS X): XDG_CACHE_HOME/cython if XDG_CACHE_HOME defined
  311. 3. ~/.cython
  312. """
  313. if 'CYTHON_CACHE_DIR' in os.environ:
  314. return os.environ['CYTHON_CACHE_DIR']
  315. parent = None
  316. if os.name == 'posix':
  317. if sys.platform == 'darwin':
  318. parent = os.path.expanduser('~/Library/Caches')
  319. else:
  320. # this could fallback on ~/.cache
  321. parent = os.environ.get('XDG_CACHE_HOME')
  322. if parent and os.path.isdir(parent):
  323. return os.path.join(parent, 'cython')
  324. # last fallback: ~/.cython
  325. return os.path.expanduser(os.path.join('~', '.cython'))
  326. @contextmanager
  327. def captured_fd(stream=2, encoding=None):
  328. pipe_in = t = None
  329. orig_stream = os.dup(stream) # keep copy of original stream
  330. try:
  331. pipe_in, pipe_out = os.pipe()
  332. os.dup2(pipe_out, stream) # replace stream by copy of pipe
  333. try:
  334. os.close(pipe_out) # close original pipe-out stream
  335. data = []
  336. def copy():
  337. try:
  338. while True:
  339. d = os.read(pipe_in, 1000)
  340. if d:
  341. data.append(d)
  342. else:
  343. break
  344. finally:
  345. os.close(pipe_in)
  346. def get_output():
  347. output = b''.join(data)
  348. if encoding:
  349. output = output.decode(encoding)
  350. return output
  351. from threading import Thread
  352. t = Thread(target=copy)
  353. t.daemon = True # just in case
  354. t.start()
  355. yield get_output
  356. finally:
  357. os.dup2(orig_stream, stream) # restore original stream
  358. if t is not None:
  359. t.join()
  360. finally:
  361. os.close(orig_stream)
  362. def print_bytes(s, header_text=None, end=b'\n', file=sys.stdout, flush=True):
  363. if header_text:
  364. file.write(header_text) # note: text! => file.write() instead of out.write()
  365. file.flush()
  366. try:
  367. out = file.buffer # Py3
  368. except AttributeError:
  369. out = file # Py2
  370. out.write(s)
  371. if end:
  372. out.write(end)
  373. if flush:
  374. out.flush()
  375. class LazyStr:
  376. def __init__(self, callback):
  377. self.callback = callback
  378. def __str__(self):
  379. return self.callback()
  380. def __repr__(self):
  381. return self.callback()
  382. def __add__(self, right):
  383. return self.callback() + right
  384. def __radd__(self, left):
  385. return left + self.callback()
  386. class OrderedSet(object):
  387. def __init__(self, elements=()):
  388. self._list = []
  389. self._set = set()
  390. self.update(elements)
  391. def __iter__(self):
  392. return iter(self._list)
  393. def update(self, elements):
  394. for e in elements:
  395. self.add(e)
  396. def add(self, e):
  397. if e not in self._set:
  398. self._list.append(e)
  399. self._set.add(e)
  400. # Class decorator that adds a metaclass and recreates the class with it.
  401. # Copied from 'six'.
  402. def add_metaclass(metaclass):
  403. """Class decorator for creating a class with a metaclass."""
  404. def wrapper(cls):
  405. orig_vars = cls.__dict__.copy()
  406. slots = orig_vars.get('__slots__')
  407. if slots is not None:
  408. if isinstance(slots, str):
  409. slots = [slots]
  410. for slots_var in slots:
  411. orig_vars.pop(slots_var)
  412. orig_vars.pop('__dict__', None)
  413. orig_vars.pop('__weakref__', None)
  414. return metaclass(cls.__name__, cls.__bases__, orig_vars)
  415. return wrapper
  416. def raise_error_if_module_name_forbidden(full_module_name):
  417. #it is bad idea to call the pyx-file cython.pyx, so fail early
  418. if full_module_name == 'cython' or full_module_name.startswith('cython.'):
  419. raise ValueError('cython is a special module, cannot be used as a module name')
  420. def build_hex_version(version_string):
  421. """
  422. Parse and translate '4.3a1' into the readable hex representation '0x040300A1' (like PY_HEX_VERSION).
  423. """
  424. # First, parse '4.12a1' into [4, 12, 0, 0xA01].
  425. digits = []
  426. release_status = 0xF0
  427. for digit in re.split('([.abrc]+)', version_string):
  428. if digit in ('a', 'b', 'rc'):
  429. release_status = {'a': 0xA0, 'b': 0xB0, 'rc': 0xC0}[digit]
  430. digits = (digits + [0, 0])[:3] # 1.2a1 -> 1.2.0a1
  431. elif digit != '.':
  432. digits.append(int(digit))
  433. digits = (digits + [0] * 3)[:4]
  434. digits[3] += release_status
  435. # Then, build a single hex value, two hex digits per version part.
  436. hexversion = 0
  437. for digit in digits:
  438. hexversion = (hexversion << 8) + digit
  439. return '0x%08X' % hexversion