forked from hakril/PythonForWindows
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleparser.py
More file actions
273 lines (228 loc) · 7.46 KB
/
Copy pathsimpleparser.py
File metadata and controls
273 lines (228 loc) · 7.46 KB
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
import collections
import StringIO
TupleToken = collections.namedtuple('Token', ['value'])
class Token(TupleToken):
def __repr__(self):
return "{0}(value={1})".format(type(self).__name__, self.value)
TupleNoValueToken = collections.namedtuple('Token', [])
class NoValueToken(TupleNoValueToken):
value = None
def __repr__(self):
return "{0}()".format(type(self).__name__)
class KeywordToken(Token):
pass
class TypeToken(Token):
pass
class NameToken(Token):
pass
class ColonToken(NoValueToken):
value = ":"
pass
class SemiColonToken(NoValueToken):
value = ";"
pass
class CommaToken(NoValueToken):
value = ","
pass
class StarToken(NoValueToken):
value = "*"
pass
class PlusToken(NoValueToken):
value = "+"
pass
class OpenBracketToken(NoValueToken):
value = "{"
pass
class CloseBracketToken(NoValueToken):
value = "}"
pass
class OpenSquareBracketToken(NoValueToken):
value = "["
pass
class CloseSquareBracketToken(NoValueToken):
value = "]"
pass
class OpenParenthesisToken(NoValueToken):
value = "("
pass
class CloseParenthesisToken(NoValueToken):
value = ")"
pass
class SharpToken(NoValueToken):
value = "#"
pass
class EqualToken(NoValueToken):
value = "="
class NewLineToken(NoValueToken):
value = "\n"
class Lexer(object):
keywords = ["typedef", "struct", "enum", "union", "const"]
token_chr = {"*" : StarToken, "[" : OpenSquareBracketToken, "]" : CloseSquareBracketToken,
"{" : OpenBracketToken, "}" : CloseBracketToken, ";" : SemiColonToken,
"," : CommaToken, "(" : OpenParenthesisToken, ")" : CloseParenthesisToken, "#" : SharpToken, "=" : EqualToken,
":": ColonToken, "+": PlusToken}
def __init__(self, code, newlinetoken=False):
self.code = code
self.newlinetoken = newlinetoken
def split_line(self, line):
return line.strip().split()
def is_keyword(self, word):
return word in self.keywords
def split_word(self, word):
"""Slit a dummy name with all token_chr"""
queue = [None, word]
for name in iter(queue.pop, None):
if name in self.token_chr:
yield self.token_chr[name]()
continue
if not any(spec_chr in name for spec_chr in self.token_chr):
yield NameToken(name)
continue
new_tokens = [name]
for spec_chr in self.token_chr:
new_tokens = list(new_tokens[0].partition(spec_chr)) + new_tokens[1:]
queue.extend(reversed([x for x in new_tokens if x]))
def __iter__(self):
for line in self.code.split("\n"):
for word in self.split_line(line):
if self.is_keyword(word):
yield KeywordToken(word)
continue
for tok in self.split_word(word):
yield tok
if self.newlinetoken:
yield NewLineToken()
class ParsingError(Exception):
pass
class Parser(object):
def __init__(self, data):
self.lexer = iter(Lexer(self.initial_processing(data)))
self.peek_token = None
def assert_keyword(self, expected_keyword, n=None):
if n is None:
n = self.assert_token_type(KeywordToken)
if n.value != expected_keyword:
raise ParsingError("Expected Keyword {0} got {1} instead".format(expected_keyword, n.value))
return n
def assert_token_type(self, expected_type, n=None):
if n is None:
n = self.next_token()
if type(n) != expected_type:
raise ParsingError("Expected type {0} and got {1} instead".format(expected_type.__name__, n))
return n
def assert_argument_io_info(self):
io_info = self.assert_token_type(NameToken)
if io_info.value not in self.known_io_info_type:
raise ParsingError("Was expection IO_INFO got {0} instead".format(winapi))
return io_info
def promote_to_type(self, token):
self.assert_token_type(NameToken, token)
return TypeToken(token.value)
def promote_to_int(self, token):
self.assert_token_type(NameToken, token)
try:
return int(token.value)
except ValueError:
return int(token.value, 0)
def next_token(self):
if self.peek_token is not None:
res = self.peek_token
self.peek_token = None
return res
return next(self.lexer, None)
def peek(self):
if self.peek_token is None:
self.peek_token = self.next_token()
return self.peek_token
def parse(self):
raise NotImplementedError("Parser.parse()")
def initial_processing(self, data):
# https://gcc.gnu.org/onlinedocs/cpp/Initial-processing.html#Initial-processing
# Step 1 -> use correct end of line + add last \n if not existing
data = data.replace("\r\n", "\n")
if not data.endswith("\n"):
data = data + "\n"
# Step 2: Trigraph : fuck it
pass
# Step 3: Line merge !
data = data.replace("\\\n", "")
# Step 4 Remove comments:
ins = StringIO.StringIO(data)
outs = StringIO.StringIO()
in_str = False
res = []
while ins.tell() != len(data):
c = ins.read(1)
if ins.tell() == len(data):
outs.write(c)
break
if not in_str and c == "/":
nc = ins.read(1)
if nc == "/":
while c != "\n":
c = ins.read(1)
outs.write(c)
continue
elif nc == "*":
while c != "*" or nc != "/":
c = nc
nc = ins.read(1)
if not nc:
raise ValueError("Unmatched */")
outs.write(" ")
continue
else:
outs.write(c)
ins.seek(ins.tell() - 1)
continue
# TODO: escape in str
elif c == '"':
in_str = not in_str
outs.write(c)
outs.seek(0)
return outs.read()
#KNOWN_TYPE = ["BYTE", "USHORT", "DWORD", "PVOID", "ULONG", "HANDLE", "PWSTR"]
#
#def validate_structs(structs):
# by_name = dict([(struct.name, struct) for struct in structs])
# if len(by_name) != len(structs):
# raise ValueError('2 structs with the same name')
#
# for struct in structs:
# for name, value in struct.typedef.items():
# by_name[name] = value
#
# for struct in structs:
# for field_type, field_name, nb_rep in struct.fields:
# if field_type.name not in KNOWN_TYPE:
# print("non standard type : {0}".format(field_type))
# if field_type.name not in by_name:
# print("UNKNOW TYPE {0}".format(field_type))
#
# return structs
#
#
#
#data = open("winfunc.txt", "r").read()
#
#
#def dbg_lexer(data):
# for i in Lexer(data).token_generation():
# print i
#
#def dbg_parser(data):
# return Parser(data).parse()
#
#def dbg_validate(data):
# return validate_structs(Parser(data).parse())
#
#
#def tst(x):
# print("=== TEST FOR <{0}> === ".format(x))
# g = Lexer("").split_word(x)
# for i in g:
# print (i)
#
#x = dbg_parser(data)
#for i in x:
# print i