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