1 import distutils.ccompiler
2 import sys, os, subprocess, glob
4 header = os.path.join('src', 'aubio.h')
5 output_path = os.path.join('python', 'gen')
7 source_header = """// this file is generated! do not modify
8 #include "aubio-types.h"
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)
51 customize_compiler(compiler)
52 except AttributeError as e:
53 print("Warning: failed customizing compiler ({:s})".format(repr(e)))
55 if hasattr(compiler, 'initialize'):
58 except ValueError as e:
59 print("Warning: failed initializing compiler ({:s})".format(repr(e)))
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()
67 elif hasattr(compiler, 'cc'): # for msvccompiler
68 cpp_cmd = compiler.cc.split()
72 print("Warning: could not guess preprocessor, using env's CC")
73 cpp_cmd = os.environ.get('CC', 'cc').split()
75 cpp_cmd += ['-x', 'c'] # force C language (emcc defaults to c++)
79 def get_c_declarations(header=header, usedouble=False):
80 ''' return a dense and preprocessed string of all c declarations implied by aubio.h
82 cpp_cmd = get_preprocessor()
84 macros = [('AUBIO_UNSTABLE', 1)]
86 macros += [('HAVE_AUBIO_DOUBLE', 1)]
88 if not os.path.isfile(header):
89 raise Exception("could not find include file " + header)
91 includes = [os.path.dirname(header)]
92 cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
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()
103 raise Exception("preprocessor output is empty:\n%s" % 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')]
109 cpp_output = filter(lambda y: len(y) > 1, cpp_output)
110 cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
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]
118 elif ('}' in cpp_output[i]):
119 cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
120 cpp_output.pop(i - 1)
124 # clean pointer notations
127 tmp+=[ l.replace(' *','* ')]
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]
139 def get_all_func_names_from_lib(lib, depth=0):
140 ''' return flat string of all function used in lib
144 for k, v in lib.items():
145 if isinstance(v, dict):
146 res += get_all_func_names_from_lib(v, depth + 1)
147 elif isinstance(v, list):
151 continue # not a function
152 fname_part = e[0].strip().split(' ')
153 fname = fname_part[-1]
157 raise NameError('gen_lib : weird function: ' + str(e))
162 def generate_lib_from_c_declarations(cpp_objects, c_declarations):
163 ''' returns a lib from given cpp_object names
165 a lib is a dict grouping functions by family (onset,pitch...)
166 each eement is itself a dict of functions grouped by puposes as :
167 struct, new, del, do, get, set and other
171 for o in cpp_objects:
173 if o[:6] == 'aubio_':
174 shortname = o[6:-2] # without aubio_
175 longname = o[:-2] # without _t
176 else: # support object not starting with aubio_ (fvec...)
180 if shortname in skip_objects:
182 lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
183 lib[shortname]['longname'] = longname
184 lib[shortname]['shortname'] = shortname
186 for fn in c_declarations:
187 func_name = fn.split('(')[0].strip().split(' ')[1:]
189 func_name = func_name[-1]
191 raise NameError('Warning : error while parsing : unexpected line %s' % fn)
192 if func_name.startswith(longname + '_') or func_name.endswith(longname):
193 # print "found", shortname, "in", fn
194 if 'typedef struct ' in fn:
195 lib[shortname]['struct'].append(fn)
197 lib[shortname]['do'].append(fn)
199 lib[shortname]['new'].append(fn)
201 lib[shortname]['del'].append(fn)
203 lib[shortname]['get'].append(fn)
205 lib[shortname]['set'].append(fn)
207 #print "no idea what to do about", fn
208 lib[shortname]['other'].append(fn)
211 def print_c_declarations_results(lib, c_declarations):
212 for fn in c_declarations:
215 for family in lib[o]:
216 if fn in lib[o][family]:
219 print ("missing", fn)
222 for family in lib[o]:
223 if type(lib[o][family]) == str:
224 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
225 elif len(lib[o][family]) == 1:
226 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
228 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
231 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
232 if not os.path.isdir(output_path): os.mkdir(output_path)
233 elif not overwrite: return sorted(glob.glob(os.path.join(output_path, '*.c')))
235 c_declarations = get_c_declarations(header, usedouble=usedouble)
236 cpp_objects = get_cpp_objects_from_c_declarations(c_declarations)
238 lib = generate_lib_from_c_declarations(cpp_objects, c_declarations)
239 # print_c_declarations_results(lib, c_declarations)
243 from .gen_code import MappedObject
244 except (SystemError, ValueError):
245 from gen_code import MappedObject
248 mapped = MappedObject(lib[o], usedouble = usedouble)
249 out += mapped.gen_code()
250 output_file = os.path.join(output_path, 'gen-%s.c' % o)
251 with open(output_file, 'w') as f:
253 print ("wrote %s" % output_file )
254 sources_list.append(output_file)
257 out += "#include \"aubio-generated.h\""
258 check_types = "\n || ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
261 int generated_types_ready (void)
263 return ({pycheck_types});
265 """.format(pycheck_types = check_types)
267 add_types = "".join(["""
268 Py_INCREF (&Py_{name}Type);
269 PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
272 void add_generated_objects ( PyObject *m )
276 """.format(add_types = add_types)
278 output_file = os.path.join(output_path, 'aubio-generated.c')
279 with open(output_file, 'w') as f:
281 print ("wrote %s" % output_file )
282 sources_list.append(output_file)
284 objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
285 out = """// generated list of objects created with gen_external.py
291 #ifndef HAVE_AUBIO_DOUBLE
292 #define HAVE_AUBIO_DOUBLE 1
297 int generated_objects ( void );
298 void add_generated_objects( PyObject *m );
299 """.format(objlist = objlist)
301 output_file = os.path.join(output_path, 'aubio-generated.h')
302 with open(output_file, 'w') as f:
304 print ("wrote %s" % output_file )
305 # no need to add header to list of sources
307 return sorted(sources_list)
309 if __name__ == '__main__':
310 if len(sys.argv) > 1: header = sys.argv[1]
311 if len(sys.argv) > 2: output_path = sys.argv[2]
312 generate_external(header, output_path)