import sys import os path if not os path exists sys argv print File no

  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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import sys
import os.path
if not os.path.exists(sys.argv[1]):
print "File %s not found" % sys.argv[1]
sys.exit(1)
from utils import status
status('Initialazing')
import os
import re
import sys
status('Loading boost submodule')
import resolve_boost_includes
from utils import read_code, find_all_files, clear_status
from config import INCLUDE_DIRS, STD_PATH
status("Compiling regular expressions")
CLASS_REGEXP=re.compile('(class|struct)\s+([A-Za-z0-9]+)(?:\s*:\s*(?:public\s+|private\s+|protected\s+){0,1}(?:(?:[a-zA-Z0-9_<>, \t]|::)+)(?:,\s*(?:public\s+|private\s+|protected\s+){0,1}(?:(?:[a-zA-Z0-9_<>, \t]|::)+))*){0,1}\s*{', re.MULTILINE)
TYPEDEF_REGEXP=re.compile('(typedef)\s+[a-zA-Z0-9_<>,\s]+\s+([a-zA-Z0-9_]+)\s*;', re.MULTILINE)
VARIABLE_REGEXP=re.compile('^\s*((?:static\s+){0,1}(?:const\s+){0,1}(?:[a-zA-Z0-9_<>,\s]|::)+)\s+([a-zA-Z0-9_]+)\s*;', re.MULTILINE)
INHARITANCE_REGEXP=re.compile('(?:class|struct)\s+[A-Za-z0-9_]+\s*:([^{]*){', re.MULTILINE)
METHOD_REGEXP = re.compile("^\s*(?!<:private:|public:|protected:)[a-zA-Z]+[a-zA-Z0-9_<>:\s,&*()]+\s+([a-zA-Z0-9_]+)\((?:[a-zA-Z0-9_<>:\s(),&*]+){0,1}\)\s*(?:const){0,1}\s*(?:(?:=\s*0\s*){0,1};|{)", re.MULTILINE)
KEYWORDS = ['auto', 'const', 'double', 'float', 'int', 'short', 'struct', 'unsigned', 'break', 'continue', 'else', 'for', 'long', 'signed', 'switch', 'void', 'case', 'default', 'enum', 'goto', 'register', 'sizeof', 'typedef', 'volatile', 'char', 'do', 'extern', 'if', 'return', 'static', 'union', 'while', 'asm', 'dynamic_cast', 'namespace', 'reinterpret_cast', 'try', 'bool', 'explicit', 'new', 'static_cast', 'typeid', 'catch', 'false', 'operator', 'template', 'typename', 'class', 'friend', 'private', 'this', 'using', 'const_cast', 'inline', 'public', 'throw', 'virtual', 'delete', 'mutable', 'protected', 'true', 'wchar_t', 'and', 'bitand', 'compl', 'not_eq', 'or_eq', 'xor_eq', 'and_eq', 'bitor', 'not', 'or', 'xor']
def resolve_class_methods(code, pos):
braces = None;
start_pos = None
end_pos = None
for i in re.finditer('{|}', code[pos:]):
if i.group() == '{':
if braces is None:
start_pos = i.start() + 1
braces = 1
else:
braces += 1
elif i.group() == '}':
if braces is None:
continue
braces -= 1
if braces == 0:
end_pos = i.start()
break
if end_pos is None:
end_pos = len(code)
start_pos += pos
end_pos += pos
methods = []
code = code[start_pos:end_pos]
for i in re.finditer(METHOD_REGEXP, code):
method = get_visibility_level({ 'pos' : i.end(), 'name': i.groups()[0]}, code)
if method['visibility'] != 'private':
methods.append(i.groups()[0])
return methods
def find_all_classes(headers):
classes = []
for header in headers:
code = read_code(header)
matchiter = re.finditer(CLASS_REGEXP, code)
local_classes = []
for match in matchiter:
value = {'name': match.groups()[1], 'pos': match.start(), 'file': header, 'type': match.groups()[0]}
if value['type'] in [ 'struct', 'class' ]:
methods = resolve_class_methods(code, match.end()-1)
methods = list(set([x for x in methods if x != value['name']]))
value['methods'] = methods
local_classes.append(value)
classes += local_classes
return classes
def find_all_typedefs(headers):
classes = []
for header in headers:
code = read_code(header)
matchiter = re.finditer(TYPEDEF_REGEXP, code)
local_classes = []
for match in matchiter:
local_classes.append({'name': match.groups()[1], 'pos': match.start(), 'file': header, 'type': match.groups()[0]})
classes += local_classes
return classes
def get_visibility_level(symbol, code):
code = code[:symbol['pos']]
structure = []
for match in re.finditer('(?<!using\s)\s*(namespace)\s+([A-Za-z0-9_]+)', code, re.MULTILINE):
structure.append({ "type": "namespace", "value": match.groups()[1], "pos": match.start()})
for match in re.finditer(CLASS_REGEXP, code):
groups = match.groups()
structure.append({ "type": groups[0], "value": groups[1], "pos": match.start()})
for match in re.finditer('({|})', code, re.MULTILINE):
structure.append({ "type": "braces", "value": match.group(), "pos": match.start()})
for match in re.finditer('^\s*(public|private|protected)\s*:', code, re.MULTILINE):
structure.append({ "type": "visibility", "value": match.groups()[0], "pos": match.start()})
#parents = [ x for x in structure if x["pos"] < symbol['pos']]
#parents.sort(key=lambda x: x['pos'])
parents = sorted(structure, key=lambda x: x['pos'])
name = []
for item in parents:
if item['type'] == 'braces':
if item['value'] == '{':
name.append(item)
if item['value'] == '}':
name.pop()
while name and name[-1]['type'] != 'braces' and name[-1]['value'] != '{':
name.pop()
elif item['type'] == 'visibility':
while name and name[-1]['type'] == 'visibility':
name.pop();
name.append(item)
else:
name.append(item)
visibility = 'public'
path = ''.join([x['value'] for x in name]) + '{'
if path.endswith('{{'):
path = path[:-1]
blocks = ''.join([x['value'] for x in name]).split('{')
if path.count('private{') or path.endswith('class{') or path.endswith('private'):
visibility = 'private'
else:
for i in blocks:
if i.endswith('private'):
visibility = 'private'
if visibility != 'private':
for i in blocks:
if i.endswith('protected'):
visibility = 'protected'
full_name = '::'.join([ x['value'] for x in name if x['type'] not in ['braces', 'visibility']] + [symbol['name']])
return {'visibility': visibility, 'full_name': full_name}
def find_all_variables(headers):
classes = []
for header in headers:
code = read_code(header)
matchiter = re.finditer(VARIABLE_REGEXP, code)
local_classes = []
for match in matchiter:
typename, name = match.groups()
typename = typename.strip()
name = name.strip()
typename = re.subn('\s+', ' ', typename)[0]
name = re.subn('\s+', ' ', name)[0]
if not typename or not name:
continue
if typename in KEYWORDS:
continue
if re.match('friend \w+', typename):
continue
if typename.startswith('return'):
continue
obj = get_visibility_level({'pos': match.start(), 'name': name}, code)
if not obj:
continue
if obj['visibility'] == 'private':
continue
local_classes.append({'full_name': obj['full_name'], 'name': name, 'typename': typename, 'type': 'var', 'file': header, 'pos': match.start()})
classes += local_classes
return classes
def resolve_classes_locations(classes):
result = []
for class_data in classes:
code = read_code(class_data['file'])
vis = get_visibility_level(class_data, code)
if not vis:
continue
if vis['visibility'] == 'private':
continue
class_data.update({'name': class_data['name'], 'full_name': vis['full_name'], 'file': class_data['file'], 'pos': class_data['pos'], 'type': class_data['type']})
result.append(class_data)
return result
def find_class_uses(sources):
res = []
for filename in sources:
#for match in re.finditer('([A-Za-z0-9_]+::(?:[A-Za-z0-9_]|::)+)\s*\(', read_code(filename), re.MULTILINE):
for match in re.finditer('([A-Za-z0-9_]+::(?:[A-Za-z0-9_]|::)+)', read_code(filename), re.MULTILINE):
res.append({'pos': match.start(), 'name': match.group(), 'file': filename, 'type': 'class'})
for match in re.finditer('new\s+((?:[A-Za-z0-9_]|::)+)', read_code(filename), re.MULTILINE):
res.append({'pos': match.start(), 'name': match.groups()[0], 'file': filename, 'type': 'class'})
for match in re.finditer('<\s*((?:[A-Za-z0-9_]|::)+)\s*>', read_code(filename), re.MULTILINE):
res.append({'pos': match.start(), 'name': match.groups()[0], 'file': filename, 'type': 'class'})
return res
def find_variable_uses(sources):
res = []
for filename in sources:
code = read_code(filename)
#for match in re.finditer('((?:[a-zA-Z0-9_]+|::)+)\s*[^\w\)^\s]+', code, re.MULTILINE):
# obj = {'name': match.groups()[0], 'file': filename, 'pos': match.start(), 'type': 'var'}
#obj.update(get_visibility_level(obj, code))
# res.append(obj)
for match in re.finditer('[^0-9a-zA-Z_:]((?:[a-zA-Z_0-9]+|::)+)[^0-9a-zA-Z_:]', code, re.MULTILINE):
obj = {'name': match.groups()[0], 'file': filename, 'pos': match.start(), 'type': 'var'}
#obj.update(get_visibility_level(obj, code))
res.append(obj)
for match in re.finditer('[^0-9a-zA-Z_]((?:[A-Z_0-9]+|::)+)[^0-9a-zA-Z_]', code, re.MULTILINE):
obj = {'name': match.groups()[0], 'file': filename, 'pos': match.start(), 'type': 'var'}
#obj.update(get_visibility_level(obj, code))
res.append(obj)
return [ x for x in res if x['name'] not in KEYWORDS ]
def lcs(xstr, ystr):
if not xstr or not ystr:
return ""
x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
if x == y:
return x + lcs(xs, ys)
else:
return max(lcs(xstr, ys), lcs(xs, ystr), key=len)
def find_location(classdata, locations):
results = []
for part in classdata['name'].split('::')[::-1]:
results = [];
for x in locations:
if x['name'] == part:
if x['type'] in ['struct', 'class' ] and (not classdata['name'].endswith(part) or classdata['name'].endswith(part + '::' + part)):
if classdata['name'].split('::')[-1] in x['methods']:
results.append(x)
else:
continue
else:
results.append(x)
if results:
break
if not results:
return []
#print classdata['name'], results
full_matches = [ x for x in results if x['full_name'] == classdata['name'] ]
if full_matches:
full_matches.sort(key=lambda x: lcs(x['full_name'].split('::'), classdata['name'].split('::')))
return full_matches[0]
results.sort(key=lambda x: -len(lcs(x['full_name'].lower().split('::'), classdata['name'].lower().split('::'))))
return results[0]
def resolve_includes(sources, locations):
class_uses = []
for filename in sources:
class_uses += find_class_uses(sources)
return resolve_uses_to_includes(class_uses, locations)
import copy
def resolve_uses_to_includes(class_uses, locations):
files = {}
deps = {}
file_uses = {}
for filename in set([ x['file'] for x in class_uses ]):
file_uses[filename] = list(set([ x['name'] for x in class_uses ]))
for use_filename in file_uses:
for name in file_uses[use_filename]:
res = find_location({'name': name}, locations)
if res and use_filename != res['file']:
if res['file'] not in deps:
deps['file'] = []
if name not in deps['file']:
deps['file'].append(name)
if use_filename not in files:
files[use_filename] = { 'symbols': [ name ], 'files': [ res['file'] ] }
else:
files[use_filename]['symbols'].append(name)
files[use_filename]['files'].append(res['file'])
includes = []
for filename in files:
for include in files[filename]['files']:
res = include
for i in INCLUDE_DIRS:
res = res.replace(i + '/', '')
includes.append('#include "%s"' % res)
includes = list(set(includes))
return includes
def find_all_class_names(sources):
names = []
for i in find_class_uses(sources):
if not i['name'].startswith('boost'):
names.append(name)
return names
def generate_namespaces(locations):
names = [ x['name'] for x in locations]
namespaces = {}
for x in locations:
name = x['name']
cur = namespaces
for i in [z for z in name.split('::') if z][:-1]:
if i not in cur:
cur[i] = {}
cur = cur[i]
if type(cur) is dict:
cur[name.split('::')[-1]] = x['type'] + ' ' + name.split('::')[-1]
return namespaces
def get_namespaces(namespaces):
def helper(namespaces, depth):
if type(namespaces) == dict:
indent = ' ' * depth
nspaces = [ [x, helper(namespaces[x], depth + 1)] for x in sorted(namespaces.keys()) if type(namespaces[x]) == dict ]
nspaces = '\n\n'.join([ indent + 'namespace ' + x[0] + '\n' + indent +'{\n' + x[1] + '\n' + indent + '}' for x in nspaces])
classes = '\n'.join(sorted([ helper(x, depth + 1) for x in namespaces.values() if type(x) != dict]))
return '\n\n'.join([ x for x in [nspaces, classes] if x])
if type(namespaces) == str:
indent = ' ' * (depth - 1)
return indent + namespaces + ';'
return helper(namespaces, 0)
def find_inheritance(sources):
symbols = []
for filename in sources:
for match in re.finditer(INHARITANCE_REGEXP, read_code(filename)):
if not match or not match.groups()[0]:
continue
for match2 in re.finditer('([a-zA-Z0-9_]|::)+', match.groups()[0]):
if match2.group() not in ['private', 'public','protected', 'class', 'typename']:
symbols.append({'name': match2.group(), 'file': filename, 'pos': match.start() + match2.start()})
return list(symbols)
def relative_path(path):
for i in INCLUDE_DIRS:
path = path.replace(i + '/', '')
return path
def find_inheritance_includes(symbols):
res = []
for symbol in symbols:
res.append(find_location(symbol, locations))
res = list(set([ x['file'] for x in res if x]))
includes = []
for item in res:
includes.append('#include "%s"' % relative_path(item))
return includes
def resolve_std_includes(filename, symbols):
std_includes = []
for i in symbols:
if i['name'].startswith('std::'):
name = i['name'].split('::')[1]
if os.path.exists('/usr/include/c++/4.2.1/%s' % name):
include = '#include <%s>' % name
if include not in std_includes:
std_includes.append(include)
if re.search('uint\d+_t', read_code(filename)):
std_includes.append("#include <stdint.h>")
std_includes.sort()
return std_includes
def get_self_name(filename):
if filename.endswith('.cpp'):
filename = filename.replace('.cpp', '.h')
return relative_path(os.path.abspath(filename))
def print_header_includes(filename):
status("Locating inheritance classes")
inh = find_inheritance([filename])
includes = find_inheritance_includes(inh)
status("Locating class uses")
names_tmp = find_class_uses([filename])
status("Resolving std includes")
std_includes = resolve_std_includes(filename, names_tmp)
status("Resolving class declarations")
names = []
typedef_includes = []
for i in names_tmp:
if not i['name'] in [ x['name'] for x in inh ]:
class_variants = []
typedef_variants = []
for j in locations:
if j['name'] == i['name'].split('::')[-1]:
if j['type'] in ['class', 'struct']:
class_variants.append(j)
else:
typedef_variants.append(j)
if class_variants:
class_variants.sort(key=lambda x: -len(lcs(x['full_name'].split('::'), i['name'].split('::'))))
i.update({'type': class_variants[0]['type']})
names.append(i)
if typedef_variants:
typedef_variants.sort(key=lambda x: -len(lcs(x['full_name'].split('::'), i['name'].split('::'))))
typedef_includes.append('#include "%s"' % relative_path(typedef_variants[0]['file']))
status("Resolving variable uses")
var_locations = find_all_variables(headers)
uses = []
for i in find_variable_uses([filename]):
locs = [ x['full_name'] for x in var_locations ]
if i in locs:
print 'adding',", ".joib([z['file'] for z in locs]), 'for', i['name']
uses += locs
status("Composing includes text")
to_remove = set()
for i in re.finditer('^\s*(?:friend\s+){0,1}(?:class|struct)\s+((?:[A-Za-z0-9_]|::)+)\s*;', read_code(filename), re.MULTILINE):
to_remove.add(i.groups()[0])
for i in find_all_classes([filename]):
to_remove.add(i['name'])
var_includes = [ '#include "%s"' % relative_path(x['file']) for x in uses ]
all_includes = sorted(list(set(includes + typedef_includes + var_includes)))
res_includes = []
for i in all_includes:
if i == '#include "%s"' % filename.split('/')[-1]:
continue
if i == '#include "%s"' % "/".join(filename.split('/')[-2:]):
continue
if i == get_self_name(filename):
continue
res_includes.append(i)
res = "\n\n\n".join([ x for x in ["\n\n".join([x for x in ['\n'.join(res_includes), '\n'.join(resolve_boost_includes.get_boost_includes(filename)), "\n".join(std_includes)] if x.strip()]), get_namespaces(generate_namespaces(names))] if x.strip()])
while res.endswith('\n\n'):
res = res[:-1]
clear_status()
print res
def print_cpp_includes(filename):
status("Locating all class uses")
symbols = find_class_uses([filename])
status("\rLocating all variable uses")
var_uses = find_variable_uses([filename])
var_uses = [ x for x in find_all_variables(headers) if x['full_name'] in [ i['name'] for i in var_uses ] ]
includes = []
sys.stdout.write("\rResolving symbols locations")
for i in sorted(resolve_uses_to_includes(symbols, locations) + [ '#include "%s"' % relative_path(x['file']) for x in var_uses ]):
if i not in includes:
includes.append(i)
status("\rResolving std includes")
std_includes = resolve_std_includes(filename, symbols)
sys.stdout.write("\rGenerating includes text")
sys.stdout.flush()
if (re.search('LOG_[A-Z]+', read_code(filename), re.MULTILINE)):
includes.append('#include "logger/logger.h"');
self = '#include "%s"' % filename.split('/')[-1].replace('.cpp', '.h')
print_self = False
if len(filename) > 4 and os.path.exists(filename[:-4] + '.h'):
print_self = True
while self in includes:
includes.remove(self)
try:
includes.remove('#include "%s"' % get_self_name(filename))
except: pass
status("\rResolving boost includes")
if print_self:
res = "\n\n".join([ x for x in [self, '\n'.join(includes), '\n'.join(resolve_boost_includes.get_boost_includes(filename)), "\n".join(std_includes)] if x.strip()])
else:
res = "\n\n".join([ x for x in ['\n'.join(includes), '\n'.join(resolve_boost_includes.get_boost_includes(filename)), "\n".join(std_includes)] if x.strip()])
while res.endswith('\n\n'):
res = res[:-1]
clear_status()
print res
status("Locating all header files")
headers = find_all_files(INCLUDE_DIRS, ".h")
status("Resolving all classes declarations")
locations = resolve_classes_locations(find_all_classes(headers)) + resolve_classes_locations(find_all_typedefs(headers))
filename = sys.argv[1]
if filename.endswith('.cpp'):
print_cpp_includes(filename)
else:
print_header_includes(filename)