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]
138 def analyze_c_declarations(cpp_objects, c_declarations):
141 for o in cpp_objects:
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...)
150 if shortname in skip_objects:
152 lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
153 lib[shortname]['longname'] = longname
154 lib[shortname]['shortname'] = shortname
156 for fn in c_declarations:
157 func_name = fn.split('(')[0].strip().split(' ')[1:]
159 func_name = func_name[-1]
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)
167 lib[shortname]['do'].append(fn)
169 lib[shortname]['new'].append(fn)
171 lib[shortname]['del'].append(fn)
173 lib[shortname]['get'].append(fn)
175 lib[shortname]['set'].append(fn)
177 #print "no idea what to do about", fn
178 lib[shortname]['other'].append(fn)
181 def print_c_declarations_results(lib, c_declarations):
182 for fn in c_declarations:
185 for family in lib[o]:
186 if fn in lib[o][family]:
189 print ("missing", fn)
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] ) )
198 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
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')))
205 c_declarations = get_c_declarations(header, usedouble=usedouble)
206 cpp_objects = get_cpp_objects_from_c_declarations(c_declarations)
208 lib = analyze_c_declarations(cpp_objects, c_declarations)
209 # print_c_declarations_results(lib, c_declarations)
213 from .gen_code import MappedObject
214 except (SystemError, ValueError):
215 from gen_code import MappedObject
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:
223 print ("wrote %s" % output_file )
224 sources_list.append(output_file)
227 out += "#include \"aubio-generated.h\""
228 check_types = "\n || ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
231 int generated_types_ready (void)
233 return ({pycheck_types});
235 """.format(pycheck_types = check_types)
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])
242 void add_generated_objects ( PyObject *m )
246 """.format(add_types = add_types)
248 output_file = os.path.join(output_path, 'aubio-generated.c')
249 with open(output_file, 'w') as f:
251 print ("wrote %s" % output_file )
252 sources_list.append(output_file)
254 objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
255 out = """// generated list of objects created with gen_external.py
261 #ifndef HAVE_AUBIO_DOUBLE
262 #define HAVE_AUBIO_DOUBLE 1
267 int generated_objects ( void );
268 void add_generated_objects( PyObject *m );
269 """.format(objlist = objlist)
271 output_file = os.path.join(output_path, 'aubio-generated.h')
272 with open(output_file, 'w') as f:
274 print ("wrote %s" % output_file )
275 # no need to add header to list of sources
277 return sorted(sources_list)
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)