gen_external.py : fix c_declaration cleaning messing with gen_code parsing of member...
[aubio.git] / python / lib / gen_external.py
1 import distutils.ccompiler
2 import sys
3 import os
4 import subprocess
5 import glob
6
7 header = os.path.join('src', 'aubio.h')
8 output_path = os.path.join('python', 'gen')
9
10 source_header = """// this file is generated! do not modify
11 #include "aubio-types.h"
12 """
13
14 skip_objects = [
15     # already in ext/
16     'fft',
17     'pvoc',
18     'filter',
19     'filterbank',
20     # AUBIO_UNSTABLE
21     'hist',
22     'parameter',
23     'scale',
24     'beattracking',
25     'resampler',
26     'peakpicker',
27     'pitchfcomb',
28     'pitchmcomb',
29     'pitchschmitt',
30     'pitchspecacf',
31     'pitchyin',
32     'pitchyinfft',
33     'sink',
34     'sink_apple_audio',
35     'sink_sndfile',
36     'sink_wavwrite',
37     #'mfcc',
38     'source',
39     'source_apple_audio',
40     'source_sndfile',
41     'source_avcodec',
42     'source_wavread',
43     #'sampler',
44     'audio_unit',
45     'spectral_whitening',
46 ]
47
48
49 def get_preprocessor():
50     # findout which compiler to use
51     from distutils.sysconfig import customize_compiler
52     compiler_name = distutils.ccompiler.get_default_compiler()
53     compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
54     try:
55         customize_compiler(compiler)
56     except AttributeError as e:
57         print("Warning: failed customizing compiler ({:s})".format(repr(e)))
58
59     if hasattr(compiler, 'initialize'):
60         try:
61             compiler.initialize()
62         except ValueError as e:
63             print("Warning: failed initializing compiler ({:s})".format(repr(e)))
64
65     cpp_cmd = None
66     if hasattr(compiler, 'preprocessor'):  # for unixccompiler
67         cpp_cmd = compiler.preprocessor
68     elif hasattr(compiler, 'compiler'):  # for ccompiler
69         cpp_cmd = compiler.compiler.split()
70         cpp_cmd += ['-E']
71     elif hasattr(compiler, 'cc'):  # for msvccompiler
72         cpp_cmd = compiler.cc.split()
73         cpp_cmd += ['-E']
74
75     if not cpp_cmd:
76         print("Warning: could not guess preprocessor, using env's CC")
77         cpp_cmd = os.environ.get('CC', 'cc').split()
78         cpp_cmd += ['-E']
79     cpp_cmd += ['-x', 'c']  # force C language (emcc defaults to c++)
80     return cpp_cmd
81
82
83 def get_c_declarations(header=header, usedouble=False):
84     ''' return a dense and preprocessed  string of all c declarations implied by aubio.h
85     '''
86     cpp_cmd = get_preprocessor()
87
88     macros = [('AUBIO_UNSTABLE', 1)]
89     if usedouble:
90         macros += [('HAVE_AUBIO_DOUBLE', 1)]
91
92     if not os.path.isfile(header):
93         raise Exception("could not find include file " + header)
94
95     includes = [os.path.dirname(header)]
96     cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
97     cpp_cmd += [header]
98
99     print("Running command: {:s}".format(" ".join(cpp_cmd)))
100     proc = subprocess.Popen(cpp_cmd,
101                             stderr=subprocess.PIPE,
102                             stdout=subprocess.PIPE)
103     assert proc, 'Proc was none'
104     cpp_output = proc.stdout.read()
105     err_output = proc.stderr.read()
106     if not cpp_output:
107         raise Exception("preprocessor output is empty:\n%s" % err_output)
108     elif err_output:
109         print("Warning: preprocessor produced warnings:\n%s" % err_output)
110     if not isinstance(cpp_output, list):
111         cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')]
112
113     cpp_output = filter(lambda y: len(y) > 1, cpp_output)
114     cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
115
116     i = 1
117     while 1:
118         if i >= len(cpp_output):
119             break
120         if ('{' in cpp_output[i - 1]) and (not '}' in cpp_output[i - 1]) or (not ';' in cpp_output[i - 1]):
121             cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
122             cpp_output.pop(i - 1)
123         elif ('}' in cpp_output[i]):
124             cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
125             cpp_output.pop(i - 1)
126         else:
127             i += 1
128
129     # clean pointer notations
130     tmp = []
131     for l in cpp_output:
132         tmp += [l.replace(' *', ' * ')]
133     cpp_output = tmp
134
135     return cpp_output
136
137
138 def get_cpp_objects_from_c_declarations(c_declarations):
139     typedefs = filter(lambda y: y.startswith('typedef struct _aubio'), c_declarations)
140     cpp_objects = [a.split()[3][:-1] for a in typedefs]
141     return cpp_objects
142
143
144 def get_all_func_names_from_lib(lib, depth=0):
145     ''' return flat string of all function used in lib
146     '''
147     res = []
148     indent = " " * depth
149     for k, v in lib.items():
150         if isinstance(v, dict):
151             res += get_all_func_names_from_lib(v, depth + 1)
152         elif isinstance(v, list):
153             for elem in v:
154                 e = elem.split('(')
155                 if len(e) < 2:
156                     continue  # not a function
157                 fname_part = e[0].strip().split(' ')
158                 fname = fname_part[-1]
159                 if fname:
160                     res += [fname]
161                 else:
162                     raise NameError('gen_lib : weird function: ' + str(e))
163
164     return res
165
166
167 def generate_lib_from_c_declarations(cpp_objects, c_declarations):
168     ''' returns a lib from given cpp_object names
169
170     a lib is a dict grouping functions by family (onset,pitch...)
171         each eement is itself a dict of functions grouped by puposes as : 
172         struct, new, del, do, get, set and other
173     '''
174     lib = {}
175
176     for o in cpp_objects:
177         shortname = o
178         if o[:6] == 'aubio_':
179             shortname = o[6:-2]  # without aubio_ prefix and _t suffix
180
181         if shortname in skip_objects:
182             continue
183
184         lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
185         lib[shortname]['longname'] = o
186         lib[shortname]['shortname'] = shortname
187
188         fullshortname = o[:-2]  # name without _t suffix
189
190         for fn in c_declarations:
191             func_name = fn.split('(')[0].strip().split(' ')[-1]
192             if func_name.startswith(fullshortname + '_') or func_name.endswith(fullshortname):
193                 # print "found", shortname, "in", fn
194                 if 'typedef struct ' in fn:
195                     lib[shortname]['struct'].append(fn)
196                 elif '_do' in fn:
197                     lib[shortname]['do'].append(fn)
198                 elif 'new_' in fn:
199                     lib[shortname]['new'].append(fn)
200                 elif 'del_' in fn:
201                     lib[shortname]['del'].append(fn)
202                 elif '_get_' in fn:
203                     lib[shortname]['get'].append(fn)
204                 elif '_set_' in fn:
205                     lib[shortname]['set'].append(fn)
206                 else:
207                     # print "no idea what to do about", fn
208                     lib[shortname]['other'].append(fn)
209     return lib
210
211
212 def print_c_declarations_results(lib, c_declarations):
213     for fn in c_declarations:
214         found = 0
215         for o in lib:
216             for family in lib[o]:
217                 if fn in lib[o][family]:
218                     found = 1
219         if found == 0:
220             print("missing", fn)
221
222     for o in lib:
223         for family in lib[o]:
224             if type(lib[o][family]) == str:
225                 print("{:15s} {:10s} {:s}".format(o, family, lib[o][family]))
226             elif len(lib[o][family]) == 1:
227                 print("{:15s} {:10s} {:s}".format(o, family, lib[o][family][0]))
228             else:
229                 print("{:15s} {:10s} {:s}".format(o, family, lib[o][family]))
230
231
232 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
233     if not os.path.isdir(output_path):
234         os.mkdir(output_path)
235     elif not overwrite:
236         return sorted(glob.glob(os.path.join(output_path, '*.c')))
237
238     c_declarations = get_c_declarations(header, usedouble=usedouble)
239     cpp_objects = get_cpp_objects_from_c_declarations(c_declarations)
240
241     lib = generate_lib_from_c_declarations(cpp_objects, c_declarations)
242     # print_c_declarations_results(lib, c_declarations)
243
244     sources_list = []
245     try:
246         from .gen_code import MappedObject
247     except (SystemError, ValueError):
248         from gen_code import MappedObject
249     for o in lib:
250         out = source_header
251         mapped = MappedObject(lib[o], usedouble=usedouble)
252         out += mapped.gen_code()
253         output_file = os.path.join(output_path, 'gen-%s.c' % o)
254         with open(output_file, 'w') as f:
255             f.write(out)
256             print("wrote %s" % output_file)
257             sources_list.append(output_file)
258
259     out = source_header
260     out += "#include \"aubio-generated.h\""
261     check_types = "\n     ||  ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
262     out += """
263
264 int generated_types_ready (void)
265 {{
266   return ({pycheck_types});
267 }}
268 """.format(pycheck_types=check_types)
269
270     add_types = "".join(["""
271   Py_INCREF (&Py_{name}Type);
272   PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name=o) for o in lib])
273     out += """
274
275 void add_generated_objects ( PyObject *m )
276 {{
277 {add_types}
278 }}
279 """.format(add_types=add_types)
280
281     output_file = os.path.join(output_path, 'aubio-generated.c')
282     with open(output_file, 'w') as f:
283         f.write(out)
284         print("wrote %s" % output_file)
285         sources_list.append(output_file)
286
287     objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
288     out = """// generated list of objects created with gen_external.py
289
290 #include <Python.h>
291 """
292     if usedouble:
293         out += """
294 #ifndef HAVE_AUBIO_DOUBLE
295 #define HAVE_AUBIO_DOUBLE 1
296 #endif
297 """
298     out += """
299 {objlist}
300 int generated_objects ( void );
301 void add_generated_objects( PyObject *m );
302 """.format(objlist=objlist)
303
304     output_file = os.path.join(output_path, 'aubio-generated.h')
305     with open(output_file, 'w') as f:
306         f.write(out)
307         print("wrote %s" % output_file)
308         # no need to add header to list of sources
309
310     return sorted(sources_list)
311
312 if __name__ == '__main__':
313     if len(sys.argv) > 1:
314         header = sys.argv[1]
315     if len(sys.argv) > 2:
316         output_path = sys.argv[2]
317     generate_external(header, output_path)