cython.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import re
  2. import SCons
  3. from SCons.Action import Action
  4. from SCons.Scanner import Scanner
  5. pyx_from_import_re = re.compile(r'^from\s+(\S+)\s+cimport', re.M)
  6. pyx_import_re = re.compile(r'^cimport\s+(\S+)', re.M)
  7. cdef_import_re = re.compile(r'^cdef extern from\s+.(\S+).:', re.M)
  8. def pyx_scan(node, env, path, arg=None):
  9. contents = node.get_text_contents()
  10. # from <module> cimport ...
  11. matches = pyx_from_import_re.findall(contents)
  12. # cimport <module>
  13. matches += pyx_import_re.findall(contents)
  14. # Modules can be either .pxd or .pyx files
  15. files = [m.replace('.', '/') + '.pxd' for m in matches]
  16. files += [m.replace('.', '/') + '.pyx' for m in matches]
  17. # cdef extern from <file>
  18. files += cdef_import_re.findall(contents)
  19. # Handle relative imports
  20. cur_dir = str(node.get_dir())
  21. files = [cur_dir + f if f.startswith('/') else f for f in files]
  22. # Filter out non-existing files (probably system imports)
  23. files = [f for f in files if env.File(f).exists()]
  24. return env.File(files)
  25. pyxscanner = Scanner(function=pyx_scan, skeys=['.pyx', '.pxd'], recursive=True)
  26. cythonAction = Action("$CYTHONCOM")
  27. def create_builder(env):
  28. try:
  29. cython = env['BUILDERS']['Cython']
  30. except KeyError:
  31. cython = SCons.Builder.Builder(
  32. action=cythonAction,
  33. emitter={},
  34. suffix=cython_suffix_emitter,
  35. single_source=1
  36. )
  37. env.Append(SCANNERS=pyxscanner)
  38. env['BUILDERS']['Cython'] = cython
  39. return cython
  40. def cython_suffix_emitter(env, source):
  41. return "$CYTHONCFILESUFFIX"
  42. def generate(env):
  43. env["CYTHON"] = "cythonize"
  44. env["CYTHONCOM"] = "$CYTHON $CYTHONFLAGS $SOURCE"
  45. env["CYTHONCFILESUFFIX"] = ".cpp"
  46. c_file, _ = SCons.Tool.createCFileBuilders(env)
  47. c_file.suffix['.pyx'] = cython_suffix_emitter
  48. c_file.add_action('.pyx', cythonAction)
  49. c_file.suffix['.py'] = cython_suffix_emitter
  50. c_file.add_action('.py', cythonAction)
  51. create_builder(env)
  52. def exists(env):
  53. return True