_cffi_gen_src.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # Integrated from the cffi-buildtool project by Rose Davidson
  2. # (https://github.com/inklesspen/cffi-buildtool), under the following
  3. # license:
  4. #
  5. # MIT License
  6. #
  7. # Copyright (c) 2024, Rose Davidson
  8. #
  9. # Permission is hereby granted, free of charge, to any person obtaining a
  10. # copy of this software and associated documentation files (the
  11. # "Software"), to deal in the Software without restriction, including
  12. # without limitation the rights to use, copy, modify, merge, publish,
  13. # distribute, sublicense, and/or sell copies of the Software, and to
  14. # permit persons to whom the Software is furnished to do so, subject to
  15. # the following conditions:
  16. #
  17. # The above copyright notice and this permission notice (including the
  18. # next paragraph) shall be included in all copies or substantial portions
  19. # of the Software.
  20. #
  21. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  24. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  25. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  26. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  27. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. """Implementation of the ``cffi-gen-src`` command-line tool.
  29. This module is private; the command line is the only supported
  30. interface. Two subcommands:
  31. ``exec-python``
  32. Execute a Python script that constructs a :class:`cffi.FFI`
  33. (the same kind of script that the CFFI docs' "Main mode of usage"
  34. describes) and emit the generated C source.
  35. ``read-sources``
  36. Create the :class:`cffi.FFI` from a separate ``cdef`` file and C
  37. source prelude, then emit the generated C source.
  38. """
  39. import argparse
  40. import io
  41. import os
  42. import sys
  43. from .api import FFI
  44. def _execfile(pysrc, filename, globs):
  45. compiled = compile(source=pysrc, filename=filename, mode='exec')
  46. exec(compiled, globs, globs)
  47. def find_ffi_in_python_script(pysrc, filename, ffivar):
  48. """Execute ``pysrc`` and return the :class:`FFI` object it defines.
  49. The script is executed with ``__name__`` set to ``"cffi.gen_src"``,
  50. so a trailing ``if __name__ == "__main__": ffibuilder.compile()``
  51. block in the script is skipped.
  52. ``ffivar`` is the name bound by the script to the :class:`FFI`
  53. object, or to a callable that returns one.
  54. Raises :class:`NameError` if the name is not bound by the script,
  55. or :class:`TypeError` if the name does not resolve to an
  56. :class:`FFI` instance.
  57. """
  58. filename = os.path.abspath(filename)
  59. globs = {'__name__': 'cffi.gen_src', '__file__': filename}
  60. old_path = sys.path[:]
  61. sys.path.insert(0, os.path.dirname(filename))
  62. try:
  63. _execfile(pysrc, filename, globs)
  64. if ffivar not in globs:
  65. raise NameError(
  66. "Expected to find the FFI object with the name %r, "
  67. "but it was not found." % (ffivar,)
  68. )
  69. ffi = globs[ffivar]
  70. if not isinstance(ffi, FFI) and callable(ffi):
  71. # Maybe it's a callable that returns a FFI
  72. ffi = ffi()
  73. if not isinstance(ffi, FFI):
  74. raise TypeError(
  75. "Found an object with the name %r but it was not an "
  76. "instance of cffi.api.FFI" % (ffivar,)
  77. )
  78. return ffi
  79. finally:
  80. sys.path[:] = old_path
  81. def make_ffi_from_sources(modulename, cdef, csrc):
  82. """Create an :class:`FFI` from ``cdef`` text and a C source prelude."""
  83. ffibuilder = FFI()
  84. ffibuilder.cdef(cdef)
  85. ffibuilder.set_source(modulename, csrc)
  86. return ffibuilder
  87. def generate_c_source(ffi):
  88. """Return the C source that :meth:`FFI.emit_c_code` would write."""
  89. output = io.StringIO()
  90. ffi.emit_c_code(output)
  91. return output.getvalue()
  92. def write_c_source(output, generated):
  93. if output == '-':
  94. sys.stdout.write(generated)
  95. return
  96. with open(output, 'w', encoding='utf-8') as f:
  97. f.write(generated)
  98. def same_input_file(file1, file2):
  99. if file1 is file2:
  100. return True
  101. try:
  102. return os.path.samefile(file1.name, file2.name)
  103. except OSError:
  104. return False
  105. def exec_python(*, output, pyfile, ffi_var):
  106. with pyfile:
  107. ffi = find_ffi_in_python_script(pyfile.read(), pyfile.name, ffi_var)
  108. generated = generate_c_source(ffi)
  109. write_c_source(output, generated)
  110. def read_sources(*, output, module_name, cdef_input, csrc_input):
  111. with csrc_input, cdef_input:
  112. csrc = csrc_input.read()
  113. cdef = cdef_input.read()
  114. ffi = make_ffi_from_sources(module_name, cdef, csrc)
  115. generated = generate_c_source(ffi)
  116. write_c_source(output, generated)
  117. def _prog():
  118. # The same parser serves both documented invocations; make --help
  119. # and usage messages show the one that was actually used.
  120. argv0 = os.path.basename(sys.argv[0]) if sys.argv else ''
  121. if argv0.startswith('cffi-gen-src'):
  122. return 'cffi-gen-src'
  123. return 'python -m cffi.gen_src'
  124. parser = argparse.ArgumentParser(
  125. prog=_prog(),
  126. description='Generate CFFI C source for extension modules.',
  127. )
  128. subparsers = parser.add_subparsers(dest='mode')
  129. exec_python_parser = subparsers.add_parser(
  130. 'exec-python',
  131. help='Execute a Python script that defines an FFI object',
  132. )
  133. exec_python_parser.add_argument(
  134. '--ffi-var',
  135. default='ffibuilder',
  136. help="Name of the FFI object in the Python script; defaults to 'ffibuilder'.",
  137. )
  138. exec_python_parser.add_argument(
  139. 'pyfile',
  140. type=argparse.FileType('r', encoding='utf-8'),
  141. help='Path to the Python script',
  142. )
  143. exec_python_parser.add_argument(
  144. 'output',
  145. help='Output path for the C source',
  146. )
  147. read_sources_parser = subparsers.add_parser(
  148. 'read-sources',
  149. help='Read cdef and C source prelude files that define an FFI object',
  150. )
  151. read_sources_parser.add_argument(
  152. 'module_name',
  153. help='Full name of the generated module, including packages',
  154. )
  155. read_sources_parser.add_argument(
  156. 'cdef',
  157. type=argparse.FileType('r', encoding='utf-8'),
  158. help='File containing C definitions',
  159. )
  160. read_sources_parser.add_argument(
  161. 'csrc',
  162. type=argparse.FileType('r', encoding='utf-8'),
  163. help='File containing C source prelude',
  164. )
  165. read_sources_parser.add_argument(
  166. 'output',
  167. help='Output path for the C source',
  168. )
  169. def run(args=None):
  170. args = parser.parse_args(args=args)
  171. if args.mode == 'exec-python':
  172. exec_python(output=args.output, pyfile=args.pyfile, ffi_var=args.ffi_var)
  173. elif args.mode == 'read-sources':
  174. if same_input_file(args.cdef, args.csrc):
  175. parser.error('cdef and csrc are the same file and should not be')
  176. read_sources(
  177. output=args.output,
  178. module_name=args.module_name,
  179. cdef_input=args.cdef,
  180. csrc_input=args.csrc,
  181. )
  182. else:
  183. parser.error('a subcommand is required: exec-python or read-sources')
  184. parser.exit(0)