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++)
78 def get_cpp_objects(header=header, usedouble=False):
79 cpp_cmd = get_preprocessor()
81 macros = [('AUBIO_UNSTABLE', 1)]
83 macros += [('HAVE_AUBIO_DOUBLE', 1)]
85 if not os.path.isfile(header):
86 raise Exception("could not find include file " + header)
88 includes = [os.path.dirname(header)]
89 cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
92 print("Running command: {:s}".format(" ".join(cpp_cmd)))
93 proc = subprocess.Popen(cpp_cmd,
94 stderr=subprocess.PIPE,
95 stdout=subprocess.PIPE)
96 assert proc, 'Proc was none'
97 cpp_output = proc.stdout.read()
98 err_output = proc.stderr.read()
100 raise Exception("preprocessor output is empty:\n%s" % err_output)
102 print ("Warning: preprocessor produced warnings:\n%s" % err_output)
103 if not isinstance(cpp_output, list):
104 cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')]
106 cpp_output = filter(lambda y: len(y) > 1, cpp_output)
107 cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
111 if i >= len(cpp_output):break
112 if ('{' in cpp_output[i - 1]) and (not '}' in cpp_output[i - 1]) or (not ';' in cpp_output[i - 1]):
113 cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
115 elif ('}' in cpp_output[i]):
116 cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
117 cpp_output.pop(i - 1)
121 typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
123 cpp_objects = [a.split()[3][:-1] for a in typedefs]
125 return cpp_output, cpp_objects
128 def analyze_cpp_output(cpp_objects, cpp_output):
131 for o in cpp_objects:
133 if o[:6] == 'aubio_':
134 shortname = o[6:-2] # without aubio_
135 longname = o[:-2] # without _t
136 else: # support object not starting with aubio_ (fvec...)
140 if shortname in skip_objects:
142 lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
143 lib[shortname]['longname'] = o
144 lib[shortname]['shortname'] = shortname
145 valid_funcname_part = ['_'+longname,longname+'_']
147 for fn in cpp_output:
148 func_name = fn.split('(')[0].strip().split(' ')[1:]
150 func_name = func_name[-1]
152 raise NameError('Warning : error while parsing : unexpected line %s' % fn)
153 if any(x in func_name for x in valid_funcname_part):
154 # print "found", shortname, "in", fn
155 if 'typedef struct ' in fn:
156 lib[shortname]['struct'].append(fn)
158 lib[shortname]['do'].append(fn)
160 lib[shortname]['new'].append(fn)
162 lib[shortname]['del'].append(fn)
164 lib[shortname]['get'].append(fn)
166 lib[shortname]['set'].append(fn)
168 #print "no idea what to do about", fn
169 lib[shortname]['other'].append(fn)
172 def print_cpp_output_results(lib, cpp_output):
173 for fn in cpp_output:
176 for family in lib[o]:
177 if fn in lib[o][family]:
180 print ("missing", fn)
183 for family in lib[o]:
184 if type(lib[o][family]) == str:
185 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
186 elif len(lib[o][family]) == 1:
187 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
189 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
192 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
193 if not os.path.isdir(output_path): os.mkdir(output_path)
194 elif not overwrite: return sorted(glob.glob(os.path.join(output_path, '*.c')))
196 cpp_output, cpp_objects = get_cpp_objects(header, usedouble=usedouble)
198 lib = analyze_cpp_output(cpp_objects, cpp_output)
199 # print_cpp_output_results(lib, cpp_output)
203 from .gen_code import MappedObject
204 except (SystemError, ValueError):
205 from gen_code import MappedObject
208 mapped = MappedObject(lib[o], usedouble = usedouble)
209 out += mapped.gen_code()
210 output_file = os.path.join(output_path, 'gen-%s.c' % o)
211 with open(output_file, 'w') as f:
213 print ("wrote %s" % output_file )
214 sources_list.append(output_file)
217 out += "#include \"aubio-generated.h\""
218 check_types = "\n || ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
221 int generated_types_ready (void)
223 return ({pycheck_types});
225 """.format(pycheck_types = check_types)
227 add_types = "".join(["""
228 Py_INCREF (&Py_{name}Type);
229 PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
232 void add_generated_objects ( PyObject *m )
236 """.format(add_types = add_types)
238 output_file = os.path.join(output_path, 'aubio-generated.c')
239 with open(output_file, 'w') as f:
241 print ("wrote %s" % output_file )
242 sources_list.append(output_file)
244 objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
245 out = """// generated list of objects created with gen_external.py
251 #ifndef HAVE_AUBIO_DOUBLE
252 #define HAVE_AUBIO_DOUBLE 1
257 int generated_objects ( void );
258 void add_generated_objects( PyObject *m );
259 """.format(objlist = objlist)
261 output_file = os.path.join(output_path, 'aubio-generated.h')
262 with open(output_file, 'w') as f:
264 print ("wrote %s" % output_file )
265 # no need to add header to list of sources
267 return sorted(sources_list)
269 if __name__ == '__main__':
270 if len(sys.argv) > 1: header = sys.argv[1]
271 if len(sys.argv) > 2: output_path = sys.argv[2]
272 generate_external(header, output_path)