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"
44 def get_preprocessor():
45 # findout which compiler to use
46 from distutils.sysconfig import customize_compiler
47 compiler_name = distutils.ccompiler.get_default_compiler()
48 compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
50 customize_compiler(compiler)
51 except AttributeError as e:
52 print("Warning: failed customizing compiler ({:s})".format(repr(e)))
54 if hasattr(compiler, 'initialize'):
57 except ValueError as e:
58 print("Warning: failed initializing compiler ({:s})".format(repr(e)))
61 if hasattr(compiler, 'preprocessor'): # for unixccompiler
62 cpp_cmd = compiler.preprocessor
63 elif hasattr(compiler, 'compiler'): # for ccompiler
64 cpp_cmd = compiler.compiler.split()
66 elif hasattr(compiler, 'cc'): # for msvccompiler
67 cpp_cmd = compiler.cc.split()
71 print("Warning: could not guess preprocessor, using env's CC")
72 cpp_cmd = os.environ.get('CC', 'cc').split()
77 def get_cpp_objects(header=header, usedouble=False):
78 cpp_cmd = get_preprocessor()
80 macros = [('AUBIO_UNSTABLE', 1)]
82 macros += [('HAVE_AUBIO_DOUBLE', 1)]
84 if not os.path.isfile(header):
85 raise Exception("could not find include file " + header)
87 includes = [os.path.dirname(header)]
88 cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
91 print("Running command: {:s}".format(" ".join(cpp_cmd)))
92 proc = subprocess.Popen(cpp_cmd,
93 stderr=subprocess.PIPE,
94 stdout=subprocess.PIPE)
95 assert proc, 'Proc was none'
96 cpp_output = proc.stdout.read()
97 err_output = proc.stderr.read()
99 raise Exception("preprocessor output is empty:\n%s" % err_output)
101 print ("Warning: preprocessor produced warnings:\n%s" % err_output)
102 if not isinstance(cpp_output, list):
103 cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')]
105 cpp_output = filter(lambda y: len(y) > 1, cpp_output)
106 cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
110 if i >= len(cpp_output): break
111 if cpp_output[i-1].endswith(',') or cpp_output[i-1].endswith('{') or cpp_output[i].startswith('}'):
112 cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
117 typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
119 cpp_objects = [a.split()[3][:-1] for a in typedefs]
121 return cpp_output, cpp_objects
124 def analyze_cpp_output(cpp_objects, cpp_output):
127 for o in cpp_objects:
128 if o[:6] != 'aubio_':
131 if shortname in skip_objects:
133 lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
134 lib[shortname]['longname'] = o
135 lib[shortname]['shortname'] = shortname
136 for fn in cpp_output:
138 #print "found", o[:-1], "in", fn
139 if 'typedef struct ' in fn:
140 lib[shortname]['struct'].append(fn)
142 lib[shortname]['do'].append(fn)
144 lib[shortname]['new'].append(fn)
146 lib[shortname]['del'].append(fn)
148 lib[shortname]['get'].append(fn)
150 lib[shortname]['set'].append(fn)
152 #print "no idea what to do about", fn
153 lib[shortname]['other'].append(fn)
156 def print_cpp_output_results(lib, cpp_output):
157 for fn in cpp_output:
160 for family in lib[o]:
161 if fn in lib[o][family]:
164 print ("missing", fn)
167 for family in lib[o]:
168 if type(lib[o][family]) == str:
169 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
170 elif len(lib[o][family]) == 1:
171 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
173 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
176 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
177 if not os.path.isdir(output_path): os.mkdir(output_path)
178 elif not overwrite: return sorted(glob.glob(os.path.join(output_path, '*.c')))
180 cpp_output, cpp_objects = get_cpp_objects(header, usedouble=usedouble)
182 lib = analyze_cpp_output(cpp_objects, cpp_output)
183 # print_cpp_output_results(lib, cpp_output)
187 from .gen_code import MappedObject
188 except (SystemError, ValueError):
189 from gen_code import MappedObject
192 mapped = MappedObject(lib[o], usedouble = usedouble)
193 out += mapped.gen_code()
194 output_file = os.path.join(output_path, 'gen-%s.c' % o)
195 with open(output_file, 'w') as f:
197 print ("wrote %s" % output_file )
198 sources_list.append(output_file)
201 out += "#include \"aubio-generated.h\""
202 check_types = "\n || ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
205 int generated_types_ready (void)
207 return ({pycheck_types});
209 """.format(pycheck_types = check_types)
211 add_types = "".join(["""
212 Py_INCREF (&Py_{name}Type);
213 PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
216 void add_generated_objects ( PyObject *m )
220 """.format(add_types = add_types)
222 output_file = os.path.join(output_path, 'aubio-generated.c')
223 with open(output_file, 'w') as f:
225 print ("wrote %s" % output_file )
226 sources_list.append(output_file)
228 objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
229 out = """// generated list of objects created with gen_external.py
235 #ifndef HAVE_AUBIO_DOUBLE
236 #define HAVE_AUBIO_DOUBLE 1
241 int generated_objects ( void );
242 void add_generated_objects( PyObject *m );
243 """.format(objlist = objlist)
245 output_file = os.path.join(output_path, 'aubio-generated.h')
246 with open(output_file, 'w') as f:
248 print ("wrote %s" % output_file )
249 # no need to add header to list of sources
251 return sorted(sources_list)
253 if __name__ == '__main__':
254 if len(sys.argv) > 1: header = sys.argv[1]
255 if len(sys.argv) > 2: output_path = sys.argv[2]
256 generate_external(header, output_path)