1 import distutils.ccompiler
7 header = os.path.join('src', 'aubio.h')
8 output_path = os.path.join('python', 'gen')
10 source_header = """// this file is generated! do not modify
11 #include "aubio-types.h"
14 default_skip_objects = [
50 def get_preprocessor():
51 # findout which compiler to use
52 from distutils.sysconfig import customize_compiler
53 compiler_name = distutils.ccompiler.get_default_compiler()
54 compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
56 customize_compiler(compiler)
57 except AttributeError as e:
58 print("Warning: failed customizing compiler ({:s})".format(repr(e)))
60 if hasattr(compiler, 'initialize'):
63 except ValueError as e:
64 print("Warning: failed initializing compiler ({:s})".format(repr(e)))
67 if hasattr(compiler, 'preprocessor'): # for unixccompiler
68 cpp_cmd = compiler.preprocessor
69 elif hasattr(compiler, 'compiler'): # for ccompiler
70 cpp_cmd = compiler.compiler.split()
72 elif hasattr(compiler, 'cc'): # for msvccompiler
73 cpp_cmd = compiler.cc.split()
77 print("Warning: could not guess preprocessor, using env's CC")
78 cpp_cmd = os.environ.get('CC', 'cc').split()
81 cpp_cmd += ['-x', 'c'] # emcc defaults to c++, force C language
85 def get_c_declarations(header=header, usedouble=False):
86 ''' return a dense and preprocessed string of all c declarations implied by aubio.h
88 cpp_cmd = get_preprocessor()
90 macros = [('AUBIO_UNSTABLE', 1)]
92 macros += [('HAVE_AUBIO_DOUBLE', 1)]
94 if not os.path.isfile(header):
95 raise Exception("could not find include file " + header)
97 includes = [os.path.dirname(header)]
98 cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
101 print("Running command: {:s}".format(" ".join(cpp_cmd)))
102 proc = subprocess.Popen(cpp_cmd,
103 stderr=subprocess.PIPE,
104 stdout=subprocess.PIPE)
105 assert proc, 'Proc was none'
106 cpp_output = proc.stdout.read()
107 err_output = proc.stderr.read()
109 print("Warning: preprocessor produced errors or warnings:\n%s" % err_output)
111 raise Exception("preprocessor output is empty:\n%s" % err_output)
112 if not isinstance(cpp_output, list):
113 cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')]
115 cpp_output = filter(lambda y: len(y) > 1, cpp_output)
116 cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
120 if i >= len(cpp_output):
122 if ('{' in cpp_output[i - 1]) and ('}' not in cpp_output[i - 1]) or (';' not in cpp_output[i - 1]):
123 cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
124 cpp_output.pop(i - 1)
125 elif ('}' in cpp_output[i]):
126 cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
127 cpp_output.pop(i - 1)
131 # clean pointer notations
134 tmp += [l.replace(' *', ' * ')]
140 def get_cpp_objects_from_c_declarations(c_declarations, skip_objects=None):
141 if skip_objects is None:
142 skip_objects = default_skip_objects
143 typedefs = filter(lambda y: y.startswith('typedef struct _aubio'), c_declarations)
144 cpp_objects = [a.split()[3][:-1] for a in typedefs]
145 cpp_objects_filtered = filter(lambda y: not y[6:-2] in skip_objects, cpp_objects)
146 return cpp_objects_filtered
149 def get_all_func_names_from_lib(lib):
150 ''' return flat string of all function used in lib
153 for _, v in lib.items():
154 if isinstance(v, dict):
155 res += get_all_func_names_from_lib(v)
156 elif isinstance(v, list):
160 continue # not a function
161 fname_part = e[0].strip().split(' ')
162 fname = fname_part[-1]
166 raise NameError('gen_lib : weird function: ' + str(e))
171 def generate_lib_from_c_declarations(cpp_objects, c_declarations):
172 ''' returns a lib from given cpp_object names
174 a lib is a dict grouping functions by family (onset,pitch...)
175 each eement is itself a dict of functions grouped by puposes as :
176 struct, new, del, do, get, set and other
180 for o in cpp_objects:
182 if o[:6] == 'aubio_':
183 shortname = o[6:-2] # without aubio_ prefix and _t suffix
185 lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'rdo': [], 'get': [], 'set': [], 'other': []}
186 lib[shortname]['longname'] = o
187 lib[shortname]['shortname'] = shortname
189 fullshortname = o[:-2] # name without _t suffix
191 for fn in c_declarations:
192 func_name = fn.split('(')[0].strip().split(' ')[-1]
193 if func_name.startswith(fullshortname + '_') or func_name.endswith(fullshortname):
194 # print "found", shortname, "in", fn
195 if 'typedef struct ' in fn:
196 lib[shortname]['struct'].append(fn)
198 lib[shortname]['do'].append(fn)
200 lib[shortname]['rdo'].append(fn)
202 lib[shortname]['new'].append(fn)
204 lib[shortname]['del'].append(fn)
206 lib[shortname]['get'].append(fn)
208 lib[shortname]['set'].append(fn)
210 # print "no idea what to do about", fn
211 lib[shortname]['other'].append(fn)
215 def print_c_declarations_results(lib, c_declarations):
216 for fn in c_declarations:
219 for family in lib[o]:
220 if fn in lib[o][family]:
226 for family in lib[o]:
227 if type(lib[o][family]) == str:
228 print("{:15s} {:10s} {:s}".format(o, family, lib[o][family]))
229 elif len(lib[o][family]) == 1:
230 print("{:15s} {:10s} {:s}".format(o, family, lib[o][family][0]))
232 print("{:15s} {:10s} {:s}".format(o, family, lib[o][family]))
235 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
236 if not os.path.isdir(output_path):
237 os.mkdir(output_path)
239 return sorted(glob.glob(os.path.join(output_path, '*.c')))
241 c_declarations = get_c_declarations(header, usedouble=usedouble)
242 cpp_objects = get_cpp_objects_from_c_declarations(c_declarations)
244 lib = generate_lib_from_c_declarations(cpp_objects, c_declarations)
245 # print_c_declarations_results(lib, c_declarations)
249 from .gen_code import MappedObject
250 except (SystemError, ValueError):
251 from gen_code import MappedObject
254 mapped = MappedObject(lib[o], usedouble=usedouble)
255 out += mapped.gen_code()
256 output_file = os.path.join(output_path, 'gen-%s.c' % o)
257 with open(output_file, 'w') as f:
259 print("wrote %s" % output_file)
260 sources_list.append(output_file)
263 out += "#include \"aubio-generated.h\""
264 check_types = "\n || ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
267 int generated_types_ready (void)
269 return ({pycheck_types});
271 """.format(pycheck_types=check_types)
273 add_types = "".join(["""
274 Py_INCREF (&Py_{name}Type);
275 PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name=o) for o in lib])
278 void add_generated_objects ( PyObject *m )
282 """.format(add_types=add_types)
284 output_file = os.path.join(output_path, 'aubio-generated.c')
285 with open(output_file, 'w') as f:
287 print("wrote %s" % output_file)
288 sources_list.append(output_file)
290 objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
291 out = """// generated list of objects created with gen_external.py
297 #ifndef HAVE_AUBIO_DOUBLE
298 #define HAVE_AUBIO_DOUBLE 1
303 int generated_objects ( void );
304 void add_generated_objects( PyObject *m );
305 """.format(objlist=objlist)
307 output_file = os.path.join(output_path, 'aubio-generated.h')
308 with open(output_file, 'w') as f:
310 print("wrote %s" % output_file)
311 # no need to add header to list of sources
313 return sorted(sources_list)
315 if __name__ == '__main__':
316 if len(sys.argv) > 1:
318 if len(sys.argv) > 2:
319 output_path = sys.argv[2]
320 generate_external(header, output_path)