Debian Codegraph @

src/cffi/_cffi_gen_src.py

raw
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
30 This module is private; the command line is the only supported
31 interface. Two subcommands:
32
33 ``exec-python``
34 Execute a Python script that constructs a :class:`cffi.FFI`
35 (the same kind of script that the CFFI docs' "Main mode of usage"
36 describes) and emit the generated C source.
37
38 ``read-sources``
39 Create the :class:`cffi.FFI` from a separate ``cdef`` file and C
40 source prelude, then emit the generated C source.
41 """
42
43 import argparse
44 import io
45 import os
46 import sys
47
48 from .api import FFI
49
50
51 def _execfile(pysrc, filename, globs):
52 compiled = compile(source=pysrc, filename=filename, mode='exec')
53 exec(compiled, globs, globs)
54
55
56 def find_ffi_in_python_script(pysrc, filename, ffivar):
57 """Execute ``pysrc`` and return the :class:`FFI` object it defines.
58
59 The script is executed with ``__name__`` set to ``"cffi.gen_src"``,
60 so a trailing ``if __name__ == "__main__": ffibuilder.compile()``
61 block in the script is skipped.
62
63 ``ffivar`` is the name bound by the script to the :class:`FFI`
64 object, or to a callable that returns one.
65
66 Raises :class:`NameError` if the name is not bound by the script,
67 or :class:`TypeError` if the name does not resolve to an
68 :class:`FFI` instance.
69 """
70 filename = os.path.abspath(filename)
71 globs = {'__name__': 'cffi.gen_src', '__file__': filename}
72 old_path = sys.path[:]
73 sys.path.insert(0, os.path.dirname(filename))
74 try:
75 _execfile(pysrc, filename, globs)
76 if ffivar not in globs:
77 raise NameError(
78 "Expected to find the FFI object with the name %r, "
79 "but it was not found." % (ffivar,)
80 )
81 ffi = globs[ffivar]
82 if not isinstance(ffi, FFI) and callable(ffi):
83 # Maybe it's a callable that returns a FFI
84 ffi = ffi()
85 if not isinstance(ffi, FFI):
86 raise TypeError(
87 "Found an object with the name %r but it was not an "
88 "instance of cffi.api.FFI" % (ffivar,)
89 )
90 return ffi
91 finally:
92 sys.path[:] = old_path
93
94
95 def make_ffi_from_sources(modulename, cdef, csrc):
96 """Create an :class:`FFI` from ``cdef`` text and a C source prelude."""
97 ffibuilder = FFI()
98 ffibuilder.cdef(cdef)
99 ffibuilder.set_source(modulename, csrc)
100 return ffibuilder
101
102
103 def generate_c_source(ffi):
104 """Return the C source that :meth:`FFI.emit_c_code` would write."""
105 output = io.StringIO()
106 ffi.emit_c_code(output)
107 return output.getvalue()
108
109
110 def write_c_source(output, generated):
111 if output == '-':
112 sys.stdout.write(generated)
113 return
114 with open(output, 'w', encoding='utf-8') as f:
115 f.write(generated)
116
117
118 def same_input_file(file1, file2):
119 if file1 is file2:
120 return True
121 try:
122 return os.path.samefile(file1.name, file2.name)
123 except OSError:
124 return False
125
126
127 def exec_python(*, output, pyfile, ffi_var):
128 with pyfile:
129 ffi = find_ffi_in_python_script(pyfile.read(), pyfile.name, ffi_var)
130 generated = generate_c_source(ffi)
131 write_c_source(output, generated)
132
133
134 def read_sources(*, output, module_name, cdef_input, csrc_input):
135 with csrc_input, cdef_input:
136 csrc = csrc_input.read()
137 cdef = cdef_input.read()
138 ffi = make_ffi_from_sources(module_name, cdef, csrc)
139 generated = generate_c_source(ffi)
140 write_c_source(output, generated)
141
142
143 def _prog():
144 # The same parser serves both documented invocations; make --help
145 # and usage messages show the one that was actually used.
146 argv0 = os.path.basename(sys.argv[0]) if sys.argv else ''
147 if argv0.startswith('cffi-gen-src'):
148 return 'cffi-gen-src'
149 return 'python -m cffi.gen_src'
150
151
152 parser = argparse.ArgumentParser(
153 prog=_prog(),
154 description='Generate CFFI C source for extension modules.',
155 )
156 subparsers = parser.add_subparsers(dest='mode')
157
158 exec_python_parser = subparsers.add_parser(
159 'exec-python',
160 help='Execute a Python script that defines an FFI object',
161 )
162 exec_python_parser.add_argument(
163 '--ffi-var',
164 default='ffibuilder',
165 help="Name of the FFI object in the Python script; defaults to 'ffibuilder'.",
166 )
167 exec_python_parser.add_argument(
168 'pyfile',
169 type=argparse.FileType('r', encoding='utf-8'),
170 help='Path to the Python script',
171 )
172 exec_python_parser.add_argument(
173 'output',
174 help='Output path for the C source',
175 )
176
177 read_sources_parser = subparsers.add_parser(
178 'read-sources',
179 help='Read cdef and C source prelude files that define an FFI object',
180 )
181 read_sources_parser.add_argument(
182 'module_name',
183 help='Full name of the generated module, including packages',
184 )
185 read_sources_parser.add_argument(
186 'cdef',
187 type=argparse.FileType('r', encoding='utf-8'),
188 help='File containing C definitions',
189 )
190 read_sources_parser.add_argument(
191 'csrc',
192 type=argparse.FileType('r', encoding='utf-8'),
193 help='File containing C source prelude',
194 )
195 read_sources_parser.add_argument(
196 'output',
197 help='Output path for the C source',
198 )
199
200
201 def run(args=None):
202 args = parser.parse_args(args=args)
203 if args.mode == 'exec-python':
204 exec_python(output=args.output, pyfile=args.pyfile, ffi_var=args.ffi_var)
205 elif args.mode == 'read-sources':
206 if same_input_file(args.cdef, args.csrc):
207 parser.error('cdef and csrc are the same file and should not be')
208 read_sources(
209 output=args.output,
210 module_name=args.module_name,
211 cdef_input=args.cdef,
212 csrc_input=args.csrc,
213 )
214 else:
215 parser.error('a subcommand is required: exec-python or read-sources')
216 parser.exit(0)