-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
class_list.cpp.py
325 lines (268 loc) · 10.2 KB
/
class_list.cpp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Written (W) 2008-2009 Soeren Sonnenburg
# Copyright (C) 2008-2009 Fraunhofer Institute FIRST and Max Planck Society
import os.path
class_str = 'class'
types = ["BOOL", "CHAR", "INT8", "UINT8", "INT16", "UINT16", "INT32", "UINT32",
"INT64", "UINT64", "FLOAT32", "FLOAT64", "FLOATMAX", "COMPLEX128"]
config_tests = ["HAVE_HDF5", "HAVE_JSON", "HAVE_XML", "HAVE_LAPACK",
"USE_CPLEX", "USE_SVMLIGHT", "USE_GLPK", "USE_LZO", "USE_GZIP",
"USE_BZIP2", "USE_LZMA", "USE_MOSEK", "HAVE_COLPACK",
"HAVE_NLOPT", "HAVE_PROTOBUF", "HAVE_VIENNACL", "USE_GPL_SHOGUN",
"USE_META_INTEGRATION_TESTS"]
SHOGUN_TEMPLATE_CLASS = "SHOGUN_TEMPLATE_CLASS"
SHOGUN_BASIC_CLASS = "SHOGUN_BASIC_CLASS"
def check_class(line):
if not (line.find('public') == -1 and
line.find('private') == -1 and
line.find('protected') == -1):
return True
def check_abstract_class(line):
line = line.replace(' ', '').replace('\t', '').strip()
return line.endswith('=0;')
def check_is_in_blacklist(c, lines, line_nr, blacklist):
ifdef_cnt = 0
for i in range(line_nr, 0, -1):
line = lines[i]
if line.find('#endif') != -1:
ifdef_cnt -= 1
if line.find('#ifdef') != -1:
ifdef_cnt += 1
for b in blacklist.keys():
if line.find(b) != -1 and ifdef_cnt > 0:
return True
if line.find('#ifndef') != -1:
ifdef_cnt += 1
return False
def extract_class_name(lines, line_nr, line, blacklist):
try:
if not line:
line = lines[line_nr]
c = line[line.index(class_str)+len(class_str):]
if ':' not in c:
return
if not check_class(line):
if not check_class(lines[line_nr+1]):
return
c = c.split()[0]
except:
return
c = c.strip(':').strip()
if not c.startswith('C'):
return
if c.endswith(';'):
return
if '>' in c:
return
if not (len(c) > 2 and c[1].isupper()):
return
if check_is_in_blacklist(c[1:], lines, line_nr, blacklist):
return
return c[1:]
def get_includes(classes, basedir=".", src_dir="shogun"):
class_headers = []
for c, t in classes:
class_headers.append(c+".h")
result = []
for root, dirs, files in os.walk(basedir):
for f in files:
if f in class_headers:
result.append(os.path.join(os.path.relpath(root, basedir), f))
includes = []
result.sort()
for o in result:
includes.append('#include <%s/%s>' % (src_dir, o.strip().lstrip('./')))
return includes
def get_definitions(classes):
definitions = []
definitions.append("#define %s" % SHOGUN_TEMPLATE_CLASS)
definitions.append("#define %s" % SHOGUN_BASIC_CLASS)
for c, t in classes:
d = "static %s CSGObject* __new_C%s(EPrimitiveType g) { return g == PT_NOT_GENERIC? new C%s(): NULL; }" % (SHOGUN_BASIC_CLASS,c,c)
definitions.append(d)
return definitions
def get_template_definitions(classes, supports_complex):
definitions = []
for c, t in classes:
d = []
d.append("static %s CSGObject* __new_C%s(EPrimitiveType g)\n{\n\tswitch (g)\n\t{\n"
% (SHOGUN_TEMPLATE_CLASS, c))
for t in types:
if t in ('BOOL', 'CHAR'):
suffix = ''
else:
suffix = '_t'
if t == 'COMPLEX128' and not supports_complex:
d.append("\t\tcase PT_COMPLEX128: return NULL;\n")
else:
d.append("\t\tcase PT_%s: return new C%s<%s%s>();\n"
% (t, c, t.lower(), suffix))
d.append("\t\tcase PT_SGOBJECT:\n")
d.append("\t\tcase PT_UNDEFINED: return NULL;\n\t}\n\treturn NULL;\n}")
definitions.append(''.join(d))
return definitions
def get_struct(classes):
struct = []
for c, template in classes:
prefix = SHOGUN_BASIC_CLASS
if template:
prefix = SHOGUN_TEMPLATE_CLASS
s = '{"%s", %s __new_C%s},' % (c, prefix, c)
struct.append(s)
return struct
def extract_block(c, lines, start_line, stop_line, start_sym, stop_sym):
sym_cnt = 0
block_start = -1
block_stop = -1
for line_nr in range(start_line, stop_line):
line = lines[line_nr]
if line.find(start_sym) != -1:
sym_cnt += 1
if block_start == -1:
block_start = line_nr
if line.find(stop_sym) != -1:
block_stop = line_nr+1
sym_cnt -= 1
if sym_cnt == 0 and block_start != -1 and block_stop != -1:
return block_start, block_stop
return block_start, block_stop
def check_complex_supported_class(line):
l = list(filter(lambda y: y if y != '' else None,
line.strip().replace('\t', ' ').split(' ')))
supported = len(l) == 3 and l[0] == 'typedef' and l[1] == 'bool' \
and l[2] == 'supports_complex128_t;'
return supported
def test_candidate(c, lines, line_nr, supports_complex):
start, stop = extract_block(c, lines, line_nr, len(lines), '{', '}')
if stop < line_nr:
return False, line_nr+1
complex_supported = False
for line_nr in range(start, stop):
line = lines[line_nr]
if line.find('virtual') != -1:
if check_abstract_class(line):
return False, stop
else:
vstart, vstop = extract_block(c, lines, line_nr,
stop, '(', ')')
for line_nr in range(vstart, vstop):
line = lines[line_nr]
if check_abstract_class(line):
return False, stop
if line.find('supports_complex128_t') != -1:
if check_complex_supported_class(line):
complex_supported = True
if not supports_complex:
return False, stop
if supports_complex and not complex_supported:
return False, stop
return True, stop
def extract_classes(HEADERS, template, blacklist, supports_complex):
"""
Search in headers for non-template/non-abstract class-names starting
with `C'.
Does not support local nor multiple classes and
drops classes with pure virtual functions
"""
classes = list()
for fname in HEADERS:
try:
lines = open(fname).readlines()
except: # python3 workaround
lines = open(fname, encoding='utf-8', errors='ignore').readlines()
line_nr = 0
while line_nr < len(lines):
line = lines[line_nr]
if line.find('IGNORE_IN_CLASSLIST') != -1:
line_nr += 1
continue
c = None
if template:
tp = line.find('template')
if tp != -1:
line = line[tp:]
cp = line.find('>')
line = line[cp+1:]
cp = line.find(class_str)
if cp != -1:
c = extract_class_name(lines, line_nr, line, blacklist)
else:
if line.find(class_str) != -1:
c = extract_class_name(lines, line_nr, None, blacklist)
if c:
ok, line_nr = test_candidate(c, lines,
line_nr, supports_complex)
if ok:
classes.append((c, template))
continue
line_nr += 1
return classes
def write_templated_file(fname, substitutes):
template = open(fname).readlines()
f = open(fname, 'w')
for line in template:
l = line.strip()
if l.startswith('REPLACE') and l.endswith('THIS'):
l = line.split()[1]
if sys.version_info >= (3,):
for s in substitutes.keys():
if l == s:
f.write('\n'.join(substitutes[s]))
continue
else:
for s in substitutes.iterkeys():
if l == s:
f.write('\n'.join(substitutes[s]))
continue
else:
f.write(line)
def read_config():
config = dict()
for line in open('lib/config.h').readlines():
if line == '\n':
continue
l = [l.strip() for l in line.split()]
config[l[1]] = 1
return config
def get_blacklist():
config = read_config()
blacklist = dict()
for cfg in config_tests:
if cfg not in config:
blacklist[cfg] = 1
return blacklist
def get_base_src_dir(headers):
return os.path.commonprefix(headers)
if __name__ == '__main__':
import sys
TEMPL_FILE = sys.argv[1]
HEADERS = None
if (sys.argv[2] == "-in"):
# read header file list from file
with open(sys.argv[3]) as f:
content = f.readlines()
HEADERS = [x.strip() for x in content]
else:
HEADERS = sys.argv[2:]
blacklist = get_blacklist()
base_src_dir = get_base_src_dir(HEADERS)
classes = extract_classes(HEADERS, False, blacklist, False)
template_classes = extract_classes(HEADERS, True, blacklist, False)
complex_template_classes = extract_classes(HEADERS, True, blacklist, True)
includes = get_includes(classes+template_classes+complex_template_classes, basedir=base_src_dir)
definitions = get_definitions(classes)
template_definitions = get_template_definitions(template_classes, False)
complex_template_definitions = get_template_definitions(complex_template_classes, True)
struct = get_struct(classes+template_classes+complex_template_classes)
substitutes = {'includes': includes,
'definitions': definitions,
'template_definitions': template_definitions,
'complex_template_definitions': complex_template_definitions,
'struct': struct
}
write_templated_file(TEMPL_FILE, substitutes)