-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathnsiqcppstyle_checker.py
1333 lines (1193 loc) · 42.7 KB
/
nsiqcppstyle_checker.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2009 NHN Inc. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of NHN Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------
import os
import traceback
from copy import deepcopy
from nsiqcppstyle_outputer import _consoleOutputer as console
from nsiqcppstyle_rulehelper import * # @UnusedWildImport
# Reserved words
tokens = [
"ID",
# Operators (+,-,*,/,%,|,&,~,^,<<,>>, ||, &&, !, <, <=, >, >=, ==, !=, <=>)
"PLUS",
"MINUS",
"TIMES",
"DIVIDE",
"MODULO",
"OR",
"AND",
"NOT",
"XOR",
"LSHIFT",
"RSHIFT",
"LOR",
"LAND",
"LNOT",
"LT",
"LE",
"GT",
"GE",
"EQ",
"NE",
"SPACESHIP",
# Assignment (=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=)
"EQUALS",
"TIMESEQUAL",
"DIVEQUAL",
"MODEQUAL",
"PLUSEQUAL",
"MINUSEQUAL",
"LSHIFTEQUAL",
"RSHIFTEQUAL",
"ANDEQUAL",
"XOREQUAL",
"OREQUAL",
# Increment/decrement (++,--)
"PLUSPLUS",
"MINUSMINUS",
# Structure dereference (->)
"ARROW",
# Ternary operator (?)
"TERNARY",
# Delimeters ( ) [ ] { } , . ; :
"LPAREN",
"RPAREN",
"PARENS",
"LBRACKET",
"RBRACKET",
"LBRACE",
"RBRACE",
"COMMA",
"PERIOD",
"SEMI",
"COLON",
"DOUBLECOLON",
# Ellipsis (...)
"ELLIPSIS",
# macro
"PREPROCESSOR",
"SHARPSHARP",
"SHARP",
# non-macro
"NUMBER",
"CHARACTER",
"STRING",
"SPACE",
"COMMENT",
"CPPCOMMENT",
"LINEFEED",
"PREPROCESSORNEXT",
"ASM",
"IGNORE",
"DEFAULT",
"DELETE",
# cast
"CONST_CAST",
"DYNAMIC_CAST",
"REINTERPRET_CAST",
"STATIC_CAST",
# control
"CONST",
"WHILE",
"IF",
"FOR",
"DO",
"ELSE",
"ENUM",
"EXPORT",
"EXTERN",
"TRUE",
"FALSE",
"GOTO",
"SWITCH",
"CASE",
"CONTST",
"CATCH",
"BREAK",
"CONTINUE",
"TRY",
"THROW",
# Operator
"NEW",
"OPERATOR",
"SIZEOF",
"INLINE",
"NAMESPACE",
"RETURN",
# visibility
"PUBLIC",
"PRIVATE",
"PROTECTED",
# Type
"STATIC",
"STRUCT",
"TEMPLATE",
"THIS",
"TYPEDEF",
"TYPENAME",
"UNION",
"USING",
"VIRTUAL",
"CLASS",
"AUTO",
"CHAR",
"INT",
"LONG",
"DOUBLE",
"FLOAT",
"SHORT",
"BOOL",
"VOID",
]
# Operators
t_PLUS = r"\+"
t_MINUS = r"-"
t_TIMES = r"\*"
t_DIVIDE = r"/"
t_MODULO = r"%"
t_OR = r"\|"
t_AND = r"&"
t_NOT = r"~"
t_XOR = r"\^"
t_LSHIFT = r"<<"
t_RSHIFT = r">>"
t_LOR = r"\|\|"
t_LAND = r"&&"
t_LNOT = r"!"
t_LT = r"<"
t_GT = r">"
t_LE = r"<="
t_GE = r">="
t_EQ = r"=="
t_NE = r"!="
t_SPACESHIP = r"<=>"
t_DOUBLECOLON = r"::"
# Assignment operators
t_PREPROCESSOR = r"\#\s*[A-Za-z_][A-Za-z0-9_]*"
t_EQUALS = r"="
t_TIMESEQUAL = r"\*="
t_DIVEQUAL = r"/="
t_MODEQUAL = r"%="
t_PLUSEQUAL = r"\+="
t_MINUSEQUAL = r"-="
t_LSHIFTEQUAL = r"<<="
t_RSHIFTEQUAL = r">>="
t_ANDEQUAL = r"&="
t_OREQUAL = r"\|="
t_XOREQUAL = r"\^="
# Increment/decrement
t_PLUSPLUS = r"\+\+"
t_MINUSMINUS = r"--"
# ->
t_ARROW = r"->"
# ?
t_TERNARY = r"\?"
# Delimiters
t_LPAREN = r"\("
t_RPAREN = r"\)"
t_LBRACKET = r"\["
t_RBRACKET = r"\]"
t_LBRACE = r"\{"
t_RBRACE = r"\}"
t_COMMA = r","
t_PERIOD = r"\."
t_SEMI = r";"
t_COLON = r":"
t_ELLIPSIS = r"\.\.\."
# Identifiers
def t_ID(t):
r"[A-Za-z_][A-Za-z0-9_]*"
t.type = reserved.get(t.value, "ID")
return t
reserved = {
"for": "FOR",
"class": "CLASS",
"asm": "ASM",
"switch": "SWITCH",
"case": "CASE",
"catch": "CATCH",
"auto": "AUTO",
"break": "BREAK",
"continue": "CONTINUE",
"default": "DEFAULT",
"delete": "DELETE",
"const_cast": "CONST_CAST",
"dynamic_cast": "DYNAMIC_CAST",
"reinterpret_cast": "REINTERPRET_CAST",
"static_cast": "STATIC_CAST",
"while": "WHILE",
"if": "IF",
"do": "DO",
"else": "ELSE",
"enum": "ENUM",
"export": "EXPORT",
"extern": "EXTERN",
"true": "TRUE",
"false": "FALSE",
"const": "CONST",
"goto": "GOTO",
"inline": "INLINE",
"namespace": "NAMESPACE",
"new": "NEW",
"operator": "OPERATOR",
"return": "RETURN",
"public": "PUBLIC",
"private": "PRIVATE",
"protected": "PROTECTED",
"sizeof": "SIZEOF",
"static": "STATIC",
"struct": "STRUCT",
"template": "TEMPLATE",
"this": "THIS",
"throw": "THROW",
"try": "TRY",
"typedef": "TYPEDEF",
"typename": "TYPENAME",
"union": "UNION",
"using": "USING",
"virtual": "VIRTUAL",
"bool": "BOOL",
"char": "CHAR",
"int": "INT",
"long": "LONG",
"double": "DOUBLE",
"float": "FLOAT",
"short": "SHORT",
"void": "VOID",
"__declspec": "IGNORE",
"volatile": "IGNORE",
"typeid": "IGNORE",
"mutable": "IGNORE",
"explicit": "IGNORE",
"friends": "IGNORE",
"register": "IGNORE",
"unsigned": "IGNORE",
"signed": "IGNORE",
"__based": "IGNORE",
"__cdecl": "IGNORE",
"__except": "IGNORE",
"__finally": "IGNORE",
"__inline": "IGNORE",
"__attribute": "IGNORE",
"__attribute__": "IGNORE",
"_based": "IGNORE",
"__stdcall": "IGNORE",
"__try": "IGNORE",
"dllexport": "IGNORE",
"final": "IGNORE",
"override": "IGNORE",
"noexcept": "IGNORE",
}
def t_IGNORE(t):
r"__attribute\(.*\)|__section\(.*\)"
return t
def t_LINEFEED(t):
r"[\n]+"
t.lexer.lineno += t.value.count("\n")
return t
def t_SPACE(t):
r"[ \t]+"
return t
t_PREPROCESSORNEXT = r"\\"
t_NUMBER = r"[0-9][0-9XxA-Fa-fL]*"
t_SHARPSHARP = r"\#\#"
t_SHARP = r"\#"
# String literal
def t_STRING(t):
r'"([^\\]|(\\.)|(\\\n))*?"'
t.lexer.lineno += t.value.count("\n")
return t
# Character constant 'c' or L'c'
t_CHARACTER = r"(L)?\'([^\\\n]|(\\.))*?\'"
# Comment (C-Style)
def t_COMMENT(t):
r"/\*(.|\n)*?\*/"
t.lexer.lineno += t.value.count("\n")
if Search(r"/\*\*\s", t.value):
t.additional = "DOXYGEN_JAVADOC"
elif Search(r"/\*\!\s", t.value):
t.additional = "DOXYGEN_QT"
return t
# Comment (C++-Style)
def t_CPPCOMMENT(t):
r"//.*"
if Search(r"^///\b", t.value):
t.additional = "DOXYGEN_CPP"
if Search(r"^///<", t.value):
t.additional = "DOXYGEN_POST"
return t
def t_error(t):
console.Out.Verbose(f"Illegal character '{t.value[0]}'", t.lexer.lineno)
t.lexer.skip(1)
class CppLexerNavigator:
"""
Main class for Cpp Lexer
"""
def __init__(self, filename, data=None):
self.filename = filename
self.tokenlist = []
self.indexstack = []
self.tokenindex = -1
self.matchingPair = {}
self.reverseMatchingPair = {}
self.ifdefstack = []
import nsiqcppstyle_lexer
lexer = nsiqcppstyle_lexer.lex()
self.data = data
if data is None:
with open(filename) as f:
try:
self.data = f.read()
except UnicodeDecodeError as ex:
console.Out.Ci("[ERROR] UnicodeDecodeError in CppLexerNavigator: " + str(ex))
console.Out.Ci(
f"[ERROR] Exception occurred reading file '{filename}', convert from UTF16LE to UTF8",
)
raise
self.lines = self.data.splitlines()
lexer.input(self.data)
index = 0
while True:
tok = lexer.token()
if not tok:
break
tok.column = self._GetColumn(tok)
tok.index = index
tok.inactive = False
index += 1
self.tokenlist.append(tok)
tok.line = self.lines[tok.lineno - 1]
tok.filename = self.filename
tok.pp = None
# self.ProcessIfdef(tok)
self.PushTokenIndex()
while True:
t = self.GetNextToken()
if t is None:
break
t.inactive = self.ProcessIfdef(t)
self.PopTokenIndex()
@property
def tokenlistsize(self):
return len(self.tokenlist)
def ProcessIfdef(self, token):
if token.type == "PREPROCESSOR":
if Match(r"^#\s*if(n)?def$", token.value):
self.ifdefstack.append(True)
elif Match(r"^#\s*if$", token.value):
nextToken = self.PeekNextTokenSkipWhiteSpaceAndComment()
if nextToken is not None and nextToken.value == "0":
self.ifdefstack.append(False)
else:
self.ifdefstack.append(True)
elif Match(r"^#\s*endif$", token.value) and len(self.ifdefstack) != 0:
self.ifdefstack.pop()
return any(not ifdef for ifdef in self.ifdefstack)
def Backup(self):
"""
Back up the current context in lexer to be restored later
"""
return (self.tokenindex, self.indexstack[:])
def Restore(self, data):
"""
Restore the lexer context.
tuple using tokenindex and indexstack should be passed
"""
self.tokenindex = data[0]
self.indexstack = data[1]
def Reset(self):
"""
Reset Lexer
"""
self.tokenindex = -1
self.indexstack = []
def GetCurTokenLine(self):
"""
Get Current Token, if No current token, return None
"""
curToken = self.GetCurToken()
if curToken is not None:
return self.lines[curToken.lineno - 1]
return None
def _MoveToToken(self, token):
self.tokenindex = token.index
def _GetColumn(self, token):
"""
Get given token column
"""
last_cr = self.data.rfind("\n", 0, token.lexpos)
if last_cr < 0:
last_cr = -1
column = token.lexpos - last_cr
if column == 0:
return 1
return column
def GetCurToken(self):
"""
Get Current Token
"""
return self.tokenlist[self.tokenindex]
def PushTokenIndex(self):
"""
Push Current Token Index into stack to keep current token.
"""
self.indexstack.append(self.tokenindex)
def PopTokenIndex(self):
"""
Pop token index stack to roll back to previously pushed token
"""
self.tokenindex = self.indexstack.pop()
def GetNextTokenSkipWhiteSpace(self):
"""
Get Next Token skip the white space.
"""
return self.GetNextToken(True)
def PeekNextToken(self):
self.PushTokenIndex()
token = self._GetNextToken()
self.PopTokenIndex()
return token
def PeekNextTokenSkipWhiteSpaceAndCommentAndPreprocess(self, offset=1):
"""
Get Next Token skip whitespace, comment and preprocess.
This method doesn't change the current lex position.
"""
self.PushTokenIndex()
token = None
for _x in range(offset): # @UnusedVariable
token = self.GetNextTokenSkipWhiteSpaceAndCommentAndPreprocess()
self.PopTokenIndex()
return token
def PeekNextTokenSkipWhiteSpaceAndComment(self):
"""
Get Next Token skip whitespace and comment.
This method doesn't change the current lex position.
"""
self.PushTokenIndex()
token = self.GetNextTokenSkipWhiteSpaceAndComment()
self.PopTokenIndex()
return token
def PeekPrevToken(self):
self.PushTokenIndex()
token = self._GetPrevToken()
self.PopTokenIndex()
return token
def PeekPrevTokenSkipWhiteSpaceAndCommentAndPreprocess(self, offset=1):
"""
Get Previous Token skip whitespace and comment.
This method doesn't change the current lex position.
"""
self.PushTokenIndex()
token = None
for _x in range(offset): # @UnusedVariable
token = self.GetPrevTokenSkipWhiteSpaceAndCommentAndPreprocess()
self.PopTokenIndex()
return token
def PeekPrevTokenSkipWhiteSpaceAndComment(self):
"""
Get Previous Token skip whitespace and comment.
This method doesn't change the current lex position.
"""
self.PushTokenIndex()
token = self.GetPrevTokenSkipWhiteSpaceAndComment()
self.PopTokenIndex()
return token
def GetNextTokenSkipWhiteSpaceAndCommentAndPreprocess(self):
"""
Get Next Token skip whitespace, comment, preprocess
This method changes the current lex position.
"""
return self.GetNextToken(True, True, True)
def GetNextTokenSkipWhiteSpaceAndComment(self):
"""
Get Next Token skip whitespace and comment.
This method changes the current lex position.
"""
return self.GetNextToken(True, True)
def GetPrevTokenSkipWhiteSpaceAndCommentAndPreprocess(self):
"""
Get Previous Token skip whitespace, comment, process.
This method changes the current lex position.
"""
return self.GetPrevToken(True, True, True)
def GetPrevTokenSkipWhiteSpaceAndComment(self):
"""
Get Previous Token skip whitespace and comment.
This method changes the current lex position.
"""
return self.GetPrevToken(True, True)
def GetNextToken(self, skipWhiteSpace=False, skipComment=False, skipDirective=False, skipMatchingBraces=False):
"""
Get Next Token with various option
- skipWhiteSpace - skip white space
- skipComment - skip comment
- skipDirective - skip preprocessor line
- skipMatchingBraces - skip all { [ ( and matching pair
"""
context = self._SkipContext(skipWhiteSpace, skipComment)
while True:
token = self._GetNextToken()
if token is None:
return token
if token.inactive is True:
continue
if skipMatchingBraces and token.type in ["LPAREN", "LBRACE", "LBRACKET"]:
self.GetNextMatchingToken()
continue
if skipDirective and token.pp is True:
continue
if token.type not in context:
if token is not None:
token.column = self._GetColumn(token)
return token
def GetNextMatchingGT(self, keepCur=False):
if keepCur:
self.PushTokenIndex()
gtStack = []
if self.GetCurToken().type != "LT":
msg = "Matching next GT token should be examined when cur token is <"
raise RuntimeError(msg)
gtStack.append(self.GetCurToken())
t = self._GetNextMatchingGTToken(gtStack)
if keepCur:
self.PopTokenIndex()
return t
def _GetNextMatchingGTToken(self, tokenStack):
while True:
nextToken = self._GetNextToken()
if nextToken is None:
return None
if nextToken.type in ["LT"]:
tokenStack.append(nextToken)
elif nextToken.type in ["GT"]:
tokenStack.pop()
if len(tokenStack) == 0:
return nextToken
elif nextToken.type in ["RSHIFT"]:
tokenStack.pop()
if len(tokenStack) == 0:
return nextToken
tokenStack.pop()
if len(tokenStack) == 0:
return nextToken
def GetNextMatchingToken(self, keepCur=False):
"""
Get matching token
"""
if keepCur:
self.PushTokenIndex()
tokenStack = []
if self.GetCurToken().type not in ["LPAREN", "LBRACE", "LBRACKET"]:
msg = "Matching token should be examined when cur token is { [ ("
raise RuntimeError(msg)
tokenStack.append(self.GetCurToken())
t = self._GetNextMatchingToken(tokenStack)
if keepCur:
self.PopTokenIndex()
return t
def _GetNextMatchingToken(self, tokenStack):
searchToken = tokenStack[-1]
matchingToken = self.matchingPair.get(searchToken, None)
lastPopedToken = None
if matchingToken is not None:
self._MoveToToken(matchingToken)
return matchingToken
while True:
nextToken = self._GetNextToken()
if nextToken is None:
if lastPopedToken in self.reverseMatchingPair:
return None
self.matchingPair[searchToken] = lastPopedToken
self.reverseMatchingPair[lastPopedToken] = searchToken
return lastPopedToken
if nextToken.type in ["LPAREN", "LBRACE", "LBRACKET"]:
tokenStack.append(nextToken)
# print "Push", nextToken
if nextToken.type in ["RPAREN", "RBRACE", "RBRACKET"]:
prevTokenPair = tokenStack[-1]
if prevTokenPair is not None:
if prevTokenPair.type[1:] == nextToken.type[1:]:
tokenStack.pop()
lastPopedToken = nextToken
if len(tokenStack) == 0:
if nextToken in self.reverseMatchingPair:
return None
self.matchingPair[searchToken] = nextToken
self.reverseMatchingPair[nextToken] = searchToken
return nextToken
else:
return None
else:
return None
def GetPrevTokenSkipWhiteSpace(self):
return self.GetPrevToken(True)
# def GetPrevTokenSkipWhiteSpaceAndComment(self):
# return self.GetPrevToken(True, True)
def GetPrevToken(self, skipWhiteSpace=False, skipComment=False, skipDirective=False, skipMatchingBraces=False):
context = self._SkipContext(skipWhiteSpace, skipComment)
while True:
token = self._GetPrevToken()
if token is None:
return token
if token.inactive:
continue
if skipMatchingBraces and token.type in ["RPAREN", "RBRACE", "RBRACKET"]:
self.GetPrevMatchingToken()
continue
if skipDirective:
line = self.GetCurTokenLine()
if Search(r"^\s*#", line):
continue
if token.type not in context:
return token
def GetPrevMatchingLT(self, keepCur=False):
if keepCur:
self.PushTokenIndex()
gtStack = []
if self.GetCurToken().type not in ["GT", "RSHIFT"]:
msg = "Matching previous LT token should be examined when cur token is > or >>"
raise RuntimeError(msg)
# If >> token is found, append it twice
if self.GetCurToken().type == "RSHIFT":
gtStack.append(self.GetCurToken())
gtStack.append(self.GetCurToken())
t = self._GetPrevMatchingLTToken(gtStack)
if keepCur:
self.PopTokenIndex()
return t
def _GetPrevMatchingLTToken(self, tokenStack):
while True:
prevToken = self._GetPrevToken()
if prevToken is None:
return None
if prevToken.type in ["GT"]:
tokenStack.append(prevToken)
elif prevToken.type in ["RSHIFT"]:
tokenStack.append(prevToken)
tokenStack.append(prevToken)
elif prevToken.type in ["LT"]:
tokenStack.pop()
if len(tokenStack) == 0:
return prevToken
def GetPrevMatchingToken(self, keepCur=False):
if keepCur:
self.PushTokenIndex()
tokenStack = []
if self.GetCurToken().type not in ["RPAREN", "RBRACE", "RBRACKET"]:
msg = "Matching token should be examined when cur token is } ) ]"
raise RuntimeError(msg)
tokenStack.append(self.GetCurToken())
t = self._GetPrevMatchingToken(tokenStack)
if keepCur:
self.PopTokenIndex()
return t
def _GetPrevMatchingToken(self, tokenStack):
searchToken = tokenStack[-1]
matchingToken = self.reverseMatchingPair.get(searchToken, None)
if matchingToken is not None:
self._MoveToToken(matchingToken)
return matchingToken
while True:
prevToken = self._GetPrevToken()
if prevToken is None:
return None
if prevToken.type in ["RPAREN", "RBRACE", "RBRACKET"]:
tokenStack.append(prevToken)
# print "Push", nextToken
elif prevToken.type in ["LPAREN", "LBRACE", "LBRACKET"]:
prevTokenPair = tokenStack[-1]
if prevTokenPair is not None:
if prevTokenPair.type[1:] == prevToken.type[1:]:
tokenStack.pop()
# print "Pop", nextToken
# print tokenStack
if len(tokenStack) == 0:
self.reverseMatchingPair[searchToken] = prevToken
self.matchingPair[prevToken] = searchToken
return prevToken
else:
return None
else:
return None
def _SkipContext(self, skipWhiteSpace=False, skipComment=False):
context = []
if skipWhiteSpace:
context.append("SPACE")
context.append("LINEFEED")
if skipComment:
context.append("COMMENT")
context.append("CPPCOMMENT")
return context
def _GetNextToken(self):
if self.tokenindex < self.tokenlistsize - 1:
self.tokenindex = self.tokenindex + 1
return self.tokenlist[self.tokenindex]
return None
def _GetPrevToken(self):
if self.tokenindex >= 0:
self.tokenindex = self.tokenindex - 1
if self.tokenindex == -1:
return None
return self.tokenlist[self.tokenindex]
return None
def GetPrevTokenInType(self, type, keepCur=True, skipPreprocess=True):
if keepCur:
self.PushTokenIndex()
token = None
while True:
token = self.GetPrevToken()
if token is None:
break
if token.type == type:
if skipPreprocess and token.pp:
continue
break
if keepCur:
self.PopTokenIndex()
return token
def GetPrevTokenInTypeList(self, typelist, keepCur=True, skipPreprocess=True):
if keepCur:
self.PushTokenIndex()
token = None
while True:
token = self.GetPrevToken(False, False, skipPreprocess, False)
if token is None:
break
if token.type in typelist:
if skipPreprocess and token.pp:
continue
break
if keepCur:
self.PopTokenIndex()
return token
def MoveToNextToken(self):
if self.tokenindex < self.tokenlistsize - 1:
self.tokenindex = self.tokenindex + 1
def MoveToPrevToken(self):
if self.tokenindex > 0:
self.tokenindex = self.tokenindex - 1
def GetNextTokenInType(self, type, keepCur=False, skipPreprocess=True):
if keepCur:
self.PushTokenIndex()
token = None
while True:
token = self.GetNextToken()
if token is None:
break
if token.type == type:
if skipPreprocess and token.pp:
continue
break
if keepCur:
self.PopTokenIndex()
return token
def GetNextTokenInTypeList(self, typelist, keepCur=False, skipPreprocess=True):
if keepCur:
self.PushTokenIndex()
token = None
while True:
token = self.GetNextToken()
if token is None:
break
if token.type in typelist:
if skipPreprocess and token.pp:
continue
break
if keepCur:
self.PopTokenIndex()
return token
def HasBody(self):
if self.GetCurToken() is None:
return False
token_id2 = self.GetNextTokenInType("LBRACE", True)
token_id3 = self.GetNextTokenInType("SEMI", True)
if token_id3 is None and token_id2 is not None:
return True
return bool(token_id2 is not None and token_id2.lexpos < token_id3.lexpos)
class Context:
def __init__(self, type, name, sig=False, starttoken=None, endtoken=None):
self.type = type
self.name = name
self.sig = sig
self.startToken = starttoken
self.endToken = endtoken
self.additional = ""
def __str__(self):
return ", ".join([self.type, "'" + self.name + "'", str(self.startToken), str(self.endToken)])
def IsContextStart(self, token):
return token == self.startToken
def IsContextEnd(self, token):
return token == self.endToken
def InScope(self, token):
return bool(token.lexpos >= self.startToken.lexpos and token.lexpos <= self.endToken.lexpos)
class ContextStack:
def __init__(self):
self.contextstack = []
def Push(self, context):
self.contextstack.append(context)
def Pop(self):
if self.Size() == 0:
return None
return self.contextstack.pop()
def Peek(self):
if self.Size() == 0:
return None
return self.contextstack[-1]
def SigPeek(self):
i = len(self.contextstack)
while True:
if i == 0:
break
i -= 1
if self.contextstack[i].sig:
return self.contextstack[i]
return None
def Size(self):
return len(self.contextstack)
def IsEmpty(self):
return len(self.contextstack) == 0
def ContainsIn(self, type):
i = len(self.contextstack)
while True:
if i == 0:
break
i -= 1
if self.contextstack[i].type == type:
return True
return False
def __str__(self):
a = ""
for eachContext in self.contextstack:
a += eachContext.__str__() + " >> "
return a