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"
47 def get_preprocessor():
48 # findout which compiler to use
49 from distutils.sysconfig import customize_compiler
50 compiler_name = distutils.ccompiler.get_default_compiler()
51 compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
53 customize_compiler(compiler)
54 except AttributeError as e:
55 print("Warning: failed customizing compiler ({:s})".format(repr(e)))
57 if hasattr(compiler, 'initialize'):
60 except ValueError as e:
61 print("Warning: failed initializing compiler ({:s})".format(repr(e)))
64 if hasattr(compiler, 'preprocessor'): # for unixccompiler
65 cpp_cmd = compiler.preprocessor
66 elif hasattr(compiler, 'compiler'): # for ccompiler
67 cpp_cmd = compiler.compiler.split()
69 elif hasattr(compiler, 'cc'): # for msvccompiler
70 cpp_cmd = compiler.cc.split()
74 print("Warning: could not guess preprocessor, using env's CC")
75 cpp_cmd = os.environ.get('CC', 'cc').split()
80 def get_cpp_objects(header=header):
81 cpp_cmd = get_preprocessor()
83 macros = [('AUBIO_UNSTABLE', 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 cpp_output[i-1].endswith(',') or cpp_output[i-1].endswith('{') or cpp_output[i].startswith('}'):
113 cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
118 typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
120 cpp_objects = [a.split()[3][:-1] for a in typedefs]
122 return cpp_output, cpp_objects
124 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
125 if not os.path.isdir(output_path): os.mkdir(output_path)
126 elif not overwrite: return glob.glob(os.path.join(output_path, '*.c'))
128 cpp_output, cpp_objects = get_cpp_objects(header)
131 for o in cpp_objects:
132 if o[:6] != 'aubio_':
135 if shortname in skip_objects:
137 lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
138 lib[shortname]['longname'] = o
139 lib[shortname]['shortname'] = shortname
140 for fn in cpp_output:
142 #print "found", o[:-1], "in", fn
143 if 'typedef struct ' in fn:
144 lib[shortname]['struct'].append(fn)
146 lib[shortname]['do'].append(fn)
148 lib[shortname]['new'].append(fn)
150 lib[shortname]['del'].append(fn)
152 lib[shortname]['get'].append(fn)
154 lib[shortname]['set'].append(fn)
156 #print "no idea what to do about", fn
157 lib[shortname]['other'].append(fn)
160 for fn in cpp_output:
163 for family in lib[o]:
164 if fn in lib[o][family]:
170 for family in lib[o]:
171 if type(lib[o][family]) == str:
172 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
173 elif len(lib[o][family]) == 1:
174 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
176 print ( "{:15s} {:10s} {:d}".format(o, family, len(lib[o][family]) ) )
180 from .gen_code import MappedObject
181 except (SystemError, ValueError):
182 from gen_code import MappedObject
185 mapped = MappedObject(lib[o], usedouble = usedouble)
186 out += mapped.gen_code()
187 output_file = os.path.join(output_path, 'gen-%s.c' % o)
188 with open(output_file, 'w') as f:
190 print ("wrote %s" % output_file )
191 sources_list.append(output_file)
194 out += "#include \"aubio-generated.h\""
195 check_types = "\n || ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
198 int generated_types_ready (void)
200 return ({pycheck_types});
202 """.format(pycheck_types = check_types)
204 add_types = "".join(["""
205 Py_INCREF (&Py_{name}Type);
206 PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
209 void add_generated_objects ( PyObject *m )
213 """.format(add_types = add_types)
215 output_file = os.path.join(output_path, 'aubio-generated.c')
216 with open(output_file, 'w') as f:
218 print ("wrote %s" % output_file )
219 sources_list.append(output_file)
221 objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
222 out = """// generated list of objects created with gen_external.py
228 #ifndef HAVE_AUBIO_DOUBLE
229 #define HAVE_AUBIO_DOUBLE 1
234 int generated_objects ( void );
235 void add_generated_objects( PyObject *m );
236 """.format(objlist = objlist)
238 output_file = os.path.join(output_path, 'aubio-generated.h')
239 with open(output_file, 'w') as f:
241 print ("wrote %s" % output_file )
242 # no need to add header to list of sources
246 if __name__ == '__main__':
247 if len(sys.argv) > 1: header = sys.argv[1]
248 if len(sys.argv) > 2: output_path = sys.argv[2]
249 generate_external(header, output_path)