-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonkParse.py
636 lines (604 loc) · 19.4 KB
/
monkParse.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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
#!/usr/bin/python
import os
import sys
import re
import copy
import monkTools as tools
sys.path.append(tools.get_current_path(__file__) + "/ply/ply/")
sys.path.append(tools.get_current_path(__file__) + "/codeBB/")
sys.path.append(tools.get_current_path(__file__) + "/codeMarkDown/")
sys.path.append(tools.get_current_path(__file__) + "/codeHL/")
import lex
import inspect
import monkDebug as debug
import monkClass as Class
import monkNamespace as Namespace
import monkStruct as Struct
import monkUnion as Union
import monkMethode as Methode
import monkEnum as Enum
import monkVariable as Variable
import monkNode as Node
import monkUsing as Using
import monkTypedef as Typedef
tokens = [
'NUMBER',
'TEMPLATE',
'NAME',
'OPEN_PAREN',
'CLOSE_PAREN',
'OPEN_BRACE',
'CLOSE_BRACE',
'OPEN_SQUARE_BRACKET',
'CLOSE_SQUARE_BRACKET',
'COLON',
'SEMI_COLON',
'COMMA',
'TAB',
'BACKSLASH',
'PIPE',
'PERCENT',
'EXCLAMATION',
'CARET',
'COMMENT_SINGLELINE_DOC_PREVIOUS',
'COMMENT_SINGLELINE_DOC',
'COMMENT_SINGLELINE',
'COMMENT_MULTILINE_DOC',
'COMMENT_MULTILINE',
'PRECOMP',
'ASTERISK',
'AMPERSTAND',
'EQUALS',
'MINUS',
'PLUS',
'DIVIDE',
'CHAR_LITERAL',
'STRING_LITERAL',
'NEW_LINE',
'SQUOTE',
]
t_ignore = " \r.?@\f"
t_TEMPLATE = r'template'
t_NUMBER = r'[0-9][0-9XxA-Fa-f]*L?'
t_NAME = r'[<>A-Za-z_~][A-Za-z0-9_]*'
t_OPEN_PAREN = r'\('
t_CLOSE_PAREN = r'\)'
t_OPEN_BRACE = r'{'
t_CLOSE_BRACE = r'}'
t_OPEN_SQUARE_BRACKET = r'\['
t_CLOSE_SQUARE_BRACKET = r'\]'
t_SEMI_COLON = r';'
t_COLON = r':'
t_COMMA = r','
def t_TAB(t):
r'\t'
t_BACKSLASH = r'\\'
t_PIPE = r'\|'
t_PERCENT = r'%'
t_CARET = r'\^'
t_EXCLAMATION = r'!'
def t_PRECOMP(t):
r'\#.*?\n'
t.value = re.sub(r'\#\#multiline\#\#', "\\\n", t.value)
t.lexer.lineno += len(list(filter(lambda a: a=="\n", t.value)))
return t
def t_COMMENT_SINGLELINE_DOC_PREVIOUS(t):
r'//(/|!)<.*?\n'
t.lexer.lineno += 1
t.value = t.value[4:]
while t.value[0] in ['\n', '\t', ' ']:
if len(t.value) <= 2:
break
t.value = t.value[1:]
while t.value[-1] in ['\n', '\t', ' ']:
if len(t.value) <= 2:
break
t.value = t.value[:-1]
return t
def t_COMMENT_SINGLELINE_DOC(t):
r'//(/|!).*?\n'
t.lexer.lineno += 1
t.value = t.value[3:]
while t.value[0] in ['\n', '\t', ' ']:
if len(t.value) <= 2:
break
t.value = t.value[1:]
while t.value[-1] in ['\n', '\t', ' ']:
if len(t.value) <= 2:
break
t.value = t.value[:-1]
return t
def t_COMMENT_SINGLELINE(t):
r'\/\/.*\n'
t.lexer.lineno += 1
t_ASTERISK = r'\*'
t_MINUS = r'\-'
t_PLUS = r'\+'
t_DIVIDE = r'/(?!/)'
t_AMPERSTAND = r'&'
t_EQUALS = r'='
t_CHAR_LITERAL = "'.'"
t_SQUOTE = "'"
#found at http://wordaligned.org/articles/string-literals-and-regular-expressions
#TODO: This does not work with the string "bla \" bla"
t_STRING_LITERAL = r'"([^"\\]|\\.)*"'
#Found at http://ostermiller.org/findcomment.html
def t_COMMENT_MULTILINE_DOC(t):
r'/\*(\*|!)(\n|.)*?\*/'
filter_result = list(filter(lambda a: a=="\n", t.value))
t.lexer.lineno += len(filter_result)
t.value = re.sub("( |\t)*\*", "", t.value[3:-2])
while t.value[0] == '\n':
if len(t.value) <= 2:
break
t.value = t.value[1:]
while t.value[-1] in ['\n', '\t', ' ']:
if len(t.value) <= 2:
break
t.value = t.value[:-1]
removeLen = 9999
listElement = t.value.split('\n')
for line in listElement:
tmpLen = 0
for element in line:
if element == ' ':
tmpLen += 1
else:
break;
if removeLen > tmpLen:
removeLen = tmpLen
if removeLen == 9999:
return t
ret = ""
isFirst = True
for line in listElement:
if isFirst == False:
ret += '\n'
isFirst = False
ret += line[removeLen:]
t.value = ret
return t
def t_COMMENT_MULTILINE(t):
r'/\*(\n|.)*?\*/'
t.lexer.lineno += len(list(filter(lambda a: a=="\n", t.value)))
def t_NEWLINE(t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(v):
print( "Lex error: ", v )
lex.lex()
##
## @brief Join the class name element : ['class', 'Bar', ':', ':', 'Foo'] -> ['class', 'Bar::Foo']
## @param table Input table to convert. ex: [':', '\t', 'class', 'Bar', ':', ':', 'Foo']
## @return The new table. ex: ['class', 'Bar::Foo']
##
def create_compleate_class_name(table):
debug.verbose("table = " + str(table))
# separate ["<XXX"] in ["<", "XXX"]
out = []
for name in table:
if len(name) > 1 \
and name[0] == "<":
out.append('<')
out.append(name[1:])
else:
out.append(name)
table = out
# convert [":", ":"] in ["::"]:
out = []
for name in table:
if len(out) == 0:
out.append(name)
elif name == ":" \
and out[-1] == ":":
out[-1] += name
else:
out.append(name)
table = out
# convert ["|", "|"] in ["||"]:
out = []
for name in table:
if len(out) == 0:
out.append(name)
elif name == "|" \
and out[-1] == "|":
out[-1] += name
else:
out.append(name)
table = out
# convert ["&", "&"] in ["&&"]:
out = []
for name in table:
if len(out) == 0:
out.append(name)
elif name == "&" \
and out[-1] == "&&":
out[-1] += name
else:
out.append(name)
table = out
#
# join operator ...
if 'operator' not in "".join(table):
out = table
else:
out = []
for name in table:
if len(out) == 0:
out.append(name)
elif out[-1][:8] == 'operator' \
and name != '(':
if out[-1] == 'operator':
out[-1] += ' '
if out[-1][-1] not in [' ', '<','>','=', '-', '!', '+', '*', '&', '|', '/']:
out[-1] += ' '
out[-1] += name
else:
out.append(name)
debug.verbose(" ==> out = " + str(out))
return out
class parse_file():
def gen_debug_space(self):
ret = "[" + str(len(self.brace_depth_type)+1) + "]"
for iii in range(0,len(self.brace_depth_type)):
ret += " "
return ret
def fusion(self, baseNode):
baseNode.fusion(self.main_node)
return baseNode
def __init__(self, fileName):
self.main_node = Node.MainNode("main-node", "tmp")
self.element_parse_stack = []
debug.debug("Parse file : '" + fileName + "'")
self.header_file_name = fileName
self.anon_union_counter = [-1, 0]
# load all the file data :
headerFileStr = tools.file_read_data(fileName)
# Strip out template declarations
# TODO : What is the real need ???
#headerFileStr = re.sub("template[\t ]*<[^>]*>", "", headerFileStr)
# remove all needed \r unneeded ==> this simplify next resExp ...
headerFileStr = re.sub("\r", "\r\n", headerFileStr)
headerFileStr = re.sub("\r\n\n", "\r\n", headerFileStr)
headerFileStr = re.sub("\r", "", headerFileStr)
# TODO : Can generate some error ...
headerFileStr = re.sub("\#if 0(.*?)(\#endif|\#else)", "", headerFileStr, flags=re.DOTALL)
headerFileafter = re.sub("\@interface(.*?)\@end", "", headerFileStr, flags=re.DOTALL)
if headerFileStr != headerFileafter :
debug.debug(" Objective C interface ... ==> not supported")
return
#debug.verbose(headerFileStr)
#Filter out Extern "C" statements. These are order dependent
headerFileStr = re.sub(r'extern( |\t)+"[Cc]"( |\t)*{', "{", headerFileStr)
headerFileStr = re.sub(r'\\\n', "##multiline##", headerFileStr)
headerFileStr += '\n'
debug.debug(headerFileStr)
###### debug.info(headerFileStr)
self.stack = [] # token stack to find the namespace and the element name ...
self.previous = None
self.name_stack = [] #
self.brace_depth = 0
self.brace_depth_type = []
self.last_comment = []
self.sub_module_count_brace = 0;
lex.lex()
lex.input(headerFileStr)
self.cur_line = 0
self.cur_char = 0
self.count_pthese = 0
while True:
tok = lex.token()
if not tok:
break
debug.verbose("TOK: " + str(tok))
self.stack.append( tok.value )
self.cur_line = tok.lineno
self.cur_char = tok.lexpos
# special case to remove internal function define in header:
if self.previous_is('function') == True:
if tok.type == 'OPEN_BRACE':
self.sub_module_count_brace += 1
debug.verbose("openBrace " + str(self.sub_module_count_brace))
elif tok.type == 'CLOSE_BRACE':
self.sub_module_count_brace -= 1
debug.verbose("closeBrace " + str(self.sub_module_count_brace) + " line:" + str(self.cur_line))
if self.sub_module_count_brace <= 0:
self.brace_type_pop()
self.last_comment = []
continue
# normal case:
if tok.type == 'PRECOMP':
debug.debug("PRECOMP: " + str(tok))
self.stack = []
self.name_stack = []
self.last_comment = []
# Do nothing for macro ==> many time not needed ...
continue
if tok.type == 'COMMENT_SINGLELINE_DOC_PREVIOUS':
if self.previous_is('enum') == True:
if self.name_stack[-1] == ",":
self.name_stack[-1] = "//!< " + tok.value
self.name_stack.append(",")
else:
self.name_stack.append("//!< " + tok.value)
elif self.previous != None \
and self.previous.get_node_type() == 'variable':
self.previous.add_doc([tok.value])
else:
#self.last_comment.append(tok.value)
pass
if tok.type == 'COMMENT_MULTILINE_DOC':
self.last_comment.append(tok.value)
if tok.type == 'COMMENT_SINGLELINE_DOC':
self.last_comment.append(tok.value)
if tok.type == 'OPEN_BRACE':
if self.count_pthese >= 1:
# special case of lamba declaration inside initialisation of constructor
self.name_stack.append(tok.value)
debug.info("plop 0 " +str(self.count_pthese))
else:
# When we open a brace, this is the time to parse the stack ...
# Clean the stack : (remove \t\r\n , and concatenate the 'xx', ':', ':', 'yy' in 'xx::yy',
self.name_stack = create_compleate_class_name(self.name_stack)
if len(self.name_stack) <= 0:
#open brace with no name ...
self.brace_type_push('empty', [])
elif is_a_function(self.name_stack):
# need to parse sub function internal description...
self.sub_module_count_brace = 1
self.brace_type_push('function', self.name_stack)
debug.verbose("openBrace *** " + str(self.name_stack))
elif 'namespace' in self.name_stack:
self.brace_type_push('namespace', self.name_stack)
elif 'class' in self.name_stack:
self.brace_type_push('class', self.name_stack)
elif 'enum' in self.name_stack:
self.brace_type_push('enum', self.name_stack)
elif 'struct' in self.name_stack:
self.brace_type_push('struct', self.name_stack)
elif 'typedef' in self.name_stack:
self.brace_type_push('typedef', self.name_stack)
elif 'using' in self.name_stack:
self.brace_type_push('using', self.name_stack)
elif 'union' in self.name_stack:
self.brace_type_push('union', self.name_stack)
else:
self.brace_type_push('unknow', self.name_stack)
self.stack = []
self.name_stack = []
self.last_comment = []
elif tok.type == 'CLOSE_BRACE':
if self.count_pthese >= 1:
debug.info("plop 2 " +str(self.count_pthese))
# special case of lamba declaration inside initialisation of constructor
self.name_stack.append(tok.value)
else:
if len(self.name_stack) != 0:
if self.previous_is('enum') == True:
self.brace_type_append('enum list', self.name_stack);
else:
debug.warning(self.gen_debug_space() + "end brace DROP : " + str(self.name_stack));
self.stack = []
self.name_stack = []
self.last_comment = []
self.brace_type_pop()
self.name_stack = create_compleate_class_name(self.name_stack)
if tok.type == 'OPEN_PAREN':
self.count_pthese += 1
self.name_stack.append(tok.value)
elif tok.type == 'CLOSE_PAREN':
self.count_pthese -= 1
self.name_stack.append(tok.value)
elif tok.type == 'OPEN_SQUARE_BRACKET':
self.name_stack.append(tok.value)
elif tok.type == 'CLOSE_SQUARE_BRACKET':
self.name_stack.append(tok.value)
elif tok.type == 'EQUALS':
self.name_stack.append(tok.value)
elif tok.type == 'COMMA':
self.name_stack.append(tok.value)
elif tok.type == 'BACKSLASH':
self.name_stack.append(tok.value)
elif tok.type == 'PIPE':
self.name_stack.append(tok.value)
elif tok.type == 'PERCENT':
self.name_stack.append(tok.value)
elif tok.type == 'CARET':
self.name_stack.append(tok.value)
elif tok.type == 'EXCLAMATION':
self.name_stack.append(tok.value)
elif tok.type == 'SQUOTE':
self.name_stack.append(tok.value)
elif tok.type == 'NUMBER':
self.name_stack.append(tok.value)
elif tok.type == 'MINUS':
self.name_stack.append(tok.value)
elif tok.type == 'PLUS':
self.name_stack.append(tok.value)
elif tok.type == 'STRING_LITERAL':
self.name_stack.append(tok.value)
elif tok.type == 'NAME' \
or tok.type == 'AMPERSTAND' \
or tok.type == 'ASTERISK' \
or tok.type == 'CHAR_LITERAL':
self.name_stack.append(tok.value)
elif tok.type == 'COLON':
if self.name_stack[0] in Node.access_list:
debug.debug(self.gen_debug_space() + "change visibility : " + self.name_stack[0]);
self.brace_type_change_access(self.name_stack[0])
self.name_stack = []
self.stack = []
else :
self.name_stack.append(tok.value)
elif tok.type == 'SEMI_COLON':
if self.count_pthese >= 1:
debug.info("plop 3 " +str(self.count_pthese))
# special case of lamba declaration inside initialisation of constructor
self.name_stack.append(tok.value)
else:
if len(self.name_stack) != 0:
self.name_stack = create_compleate_class_name(self.name_stack)
if is_a_function(self.name_stack):
self.brace_type_append('function', self.name_stack);
elif 'namespace' in self.name_stack:
debug.debug(self.gen_debug_space() + "find a namespace DECLARATION : " + str(self.name_stack));
elif 'class' in self.name_stack:
debug.debug(self.gen_debug_space() + "find a class DECLARATION : " + str(self.name_stack));
elif 'enum' in self.name_stack:
debug.debug(self.gen_debug_space() + "find a enum DECLARATION : " + str(self.name_stack));
elif 'struct' in self.name_stack:
debug.debug(self.gen_debug_space() + "find a struct DECLARATION : " + str(self.name_stack));
elif 'typedef' in self.name_stack:
debug.warning(self.gen_debug_space() + "find a typedef DECLARATION : " + str(self.name_stack) + " ==> lose it ...");
#self.brace_type_push('typedef', self.name_stack);
elif 'using' in self.name_stack:
debug.info(self.gen_debug_space() + "find a using DECLARATION : " + str(self.name_stack));
self.brace_type_append('using', self.name_stack);
elif 'union' in self.name_stack:
debug.debug(self.gen_debug_space() + "find a union DECLARATION : " + str(self.name_stack));
else:
if self.previous_is('enum') == True:
self.brace_type_append('enum list', self.name_stack);
else:
# TODO : Check if it is true in all case :
self.brace_type_append('variable', self.name_stack);
#debug.warning(self.gen_debug_space() + "variable : " + str(self.name_stack));
self.stack = []
self.name_stack = []
self.last_comment = []
#self.debug_display();
def debug_display(self):
debug.info("Debug display :")
self.main_node.debug_display(1)
def create_element(self, type, stack):
ret = None
self.previous = None
if type == 'empty' \
or type == 'enum list':
pass
elif type == 'namespace':
ret = Namespace.Namespace(stack, self.header_file_name, self.cur_line, self.last_comment)
elif type == 'class':
ret = Class.Class(stack, self.header_file_name, self.cur_line, self.last_comment)
elif type == 'struct':
ret = Struct.Struct(stack, self.header_file_name, self.cur_line, self.last_comment)
elif type == 'typedef':
ret = Typedef.Typedef(stack, self.header_file_name, self.cur_line)
elif type == 'using':
ret = Using.Using(stack, self.header_file_name, self.cur_line)
elif type == 'union':
ret = Union.Union(stack, self.header_file_name, self.cur_line, self.last_comment)
elif type == 'function':
#debug.info(str(self.last_comment))
if self.get_last_type() == 'class':
ret = Methode.Methode(stack, self.header_file_name, self.cur_line, self.last_comment, self.brace_depth_type[len(self.brace_depth_type)-1]['node'].get_name())
else:
ret = Methode.Methode(stack, self.header_file_name, self.cur_line, self.last_comment)
elif type == 'enum':
ret = Enum.Enum(stack, self.header_file_name, self.cur_line, self.last_comment)
elif type == 'variable':
ret = Variable.Variable(stack, self.header_file_name, self.cur_line, self.last_comment)
self.previous = ret
else:
debug.error("unknow type ...")
return ret
def brace_type_push(self, type, stack):
debug.debug(self.gen_debug_space() + "find a <<" + type + ">> : " + str(stack));
myClassElement = self.create_element(type, stack)
element = { 'type' : type,
'stack' : stack,
'node' : myClassElement
}
self.brace_depth_type.append(element)
#debug.info ("append : " + str(element))
def brace_type_append_current(self, element, id = -50):
if id == -50:
id = len(self.brace_depth_type)-1
if id >= 0:
while self.brace_depth_type[id]['node'] == None:
# special case for empty brace, just add it to the upper
id -=1
if id < 0:
break;
if id < 0:
self.main_node.append(element)
else:
self.brace_depth_type[id]['node'].append(element)
def brace_type_append(self, type, stack):
debug.debug(self.gen_debug_space() + " append a <<" + type + ">> : " + str(stack));
lastType = self.get_last_type()
newType = self.create_element(type, stack)
if newType != None:
self.brace_type_append_current(newType)
return
# enum sub list:
if lastType == 'enum' \
and type == 'enum list':
id = len(self.brace_depth_type)-1
self.brace_depth_type[id]['node'].enum_append(stack)
return
debug.info("TODO : Parse the special type")
def brace_type_pop(self):
id = len(self.brace_depth_type)-1
if id < 0:
debug.warning("Try to pop the stack with No more element ...")
return
if self.brace_depth_type[id]['node'] == None:
# nothing to add at the upper ...
pass
else:
# add it on the previous
self.brace_type_append_current(self.brace_depth_type[id]['node'], id-1)
self.brace_depth_type.pop()
def brace_type_change_access(self, newOne):
if newOne not in Node.access_list:
debug.error("unknow access type : " + newOne)
return
id = len(self.brace_depth_type)-1
if id >= 0:
while self.brace_depth_type[id]['node'] == None:
# special case for empty brace, just add it to the upper
id -=1
if id < 0:
break;
if id < 0:
debug.warning("can not change the main access on the library")
else:
if self.brace_depth_type[id]['node'].get_access() == None:
debug.error("Can not set access in other as : 'class' or 'struct' :" + str(self.brace_depth_type[id]))
return
self.brace_depth_type[id]['node'].set_access(newOne)
def previous_is(self, type):
if self.get_last_type() == type:
return True
return False
def get_last_type(self):
if len(self.brace_depth_type) > 0:
return self.brace_depth_type[len(self.brace_depth_type)-1]['type']
return None
def is_a_function(stack) :
# in a function we need to have functionName + ( + )
tmp = copy.deepcopy(stack);
while len(tmp) > 0\
and ( tmp[-1] == 'const'\
or tmp[-1] == 'noexcept'\
or tmp[-1] == 'override'\
or tmp[-1] == 'volatile'):
tmp = tmp[:-1]
if len(tmp) < 3:
return False
if ':' in tmp:
res = []
for element in tmp:
if element != ':':
res.append(element)
else:
break
tmp = res
if tmp[-2] == '=' \
and tmp[-1] == '0':
tmp = tmp[:-2]
#can end with 2 possibilities : ')', 'const' or ')'
if tmp[-1] == ')':
return True
return False