-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.py
285 lines (258 loc) · 11.3 KB
/
scanner.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
import tokens
class charstream:
''' An iterator on characters that supports arbitrary long
readahead '''
def __init__(self,filename):
self.filename = filename
def __iter__(self):
self.linestream = open(self.filename)
# currentline may be more than one line when readahead is used
self.currentline = ""
self.ln = 1 # Line number
self.col = 0 # next character we'll read from currentline
return self
def __next__(self):
if self.col >= len(self.currentline):
self.currentline = next(self.linestream)
# if this fails, we reached the end of the file and
# chars() itself will terminate.
self.col = 0
if self.currentline[self.col] == '\n':
self.ln += 1
self.col += 1
return self.currentline[self.col-1]
def skip(self,count):
self.ln += self.currentline[self.col:self.col+count].count("\n")
self.col += count
def linenumber(self):
return self.ln
def readahead(self,count):
''' Return the count next characters without consuming them,
or None if there aren't that many characters left in the file
'''
try:
while len(self.currentline)-self.col < count:
self.currentline += next(self.linestream)
return self.currentline[self.col:self.col+count]
except StopIteration:
return None
def startswith(self,prefix):
''' if the next few characters are equal to the prefix,
consume them and return True. Otherwise do nothing and return
False. '''
if self.readahead(len(prefix)) == prefix:
self.skip(len(prefix))
return True
else:
return False
def startswithwhite(self):
''' return True if the next character is a whitespace '''
c = self.readahead(1)
return c in ' \t\n'
def startswithnumeric(self):
''' return True if the next character is a number '''
c = self.readahead(1)
return c in '0123456789'
def startswithalpha(self):
''' return True if the next character can _start_ a keyword or
function name '''
c = self.readahead(1)
return c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
def startswithalphanumeric(self):
''' return True if the next character can _continue_ an
identifier, keyword or function name '''
c = self.readahead(1)
return c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_012356789'
def scanfile(stream):
try:
while True:
if stream.startswith('<?php'):
# print('starting php block')
while not stream.startswith('?>'):
if stream.startswithwhite():
next(stream)
elif stream.startswith('/*'):
while not stream.startswith('*/'):
next(stream)
# yield (tokens.Comment,)
elif stream.startswith('//'):
while not stream.startswith('\n'):
next(stream)
# yield (tokens.Comment,)
elif stream.startswith(';'):
yield (tokens.Semicolon,)
elif stream.startswith(','):
yield (tokens.Comma,)
elif stream.startswith('.='):
yield (tokens.CatAssign,)
elif stream.startswith('.'):
yield (tokens.Period,)
elif stream.startswith('('):
yield (tokens.OpeningBracket,)
elif stream.startswith(')'):
yield (tokens.ClosingBracket,)
elif stream.startswith('['):
yield (tokens.OpeningSquareBracket,)
elif stream.startswith(']'):
yield (tokens.ClosingSquareBracket,)
elif stream.startswith('{'):
yield (tokens.OpeningCurly,)
elif stream.startswith('}'):
yield (tokens.ClosingCurly,)
elif stream.startswith('<='):
yield (tokens.LessOrEqual,)
elif stream.startswith('<'):
yield (tokens.LessThan,)
elif stream.startswith('>='):
yield (tokens.GreaterOrEqual,)
elif stream.startswith('>'):
yield (tokens.GreaterThan,)
elif stream.startswith('==='):
yield (tokens.EqualsExactly,)
elif stream.startswith('=='):
yield (tokens.Equals,)
elif stream.startswith('=>'):
yield (tokens.MapsTo,)
elif stream.startswith('='):
yield (tokens.Assign,)
elif stream.startswith('++'):
yield (tokens.Increment,)
elif stream.startswith('+='):
yield (tokens.PlusAssign,)
elif stream.startswith('+'):
yield (tokens.Plus,)
elif stream.startswith('-='):
yield (tokens.MinusAssign,)
elif stream.startswith('--'):
yield (tokens.Decrement,)
elif stream.startswith('-'):
yield (tokens.Minus,)
elif stream.startswith('*'):
yield (tokens.Times,)
elif stream.startswith('/'):
yield (tokens.Divide,)
elif stream.startswith('%'):
yield (tokens.Modulo,)
elif stream.startswith('&&'):
yield (tokens.BooleanAnd,)
elif stream.startswith('&'):
yield (tokens.Ampersand,)
elif stream.startswith('||'):
yield (tokens.BooleanOr,)
elif stream.startswith('|'):
yield (tokens.Pipe,)
elif stream.startswith('!=='):
yield (tokens.NotEqualsExactly,)
elif stream.startswith('!='):
yield (tokens.NotEquals,)
elif stream.startswith('!'):
yield (tokens.BooleanNot,)
elif stream.startswith('?'):
yield (tokens.Question,)
elif stream.startswith(':'):
yield (tokens.Colon,)
elif stream.startswith('"'):
s=''
while not stream.startswith('"'):
if stream.startswith('\\'):
# when seeing a backslash, reading the
# next char even if it's a "
pass
s += next(stream)
yield (tokens.String,s)
elif stream.startswith("'"):
s=''
while not stream.startswith("'"):
if stream.startswith('\\'):
# when seeing a backslash, reading the
# next char even if it's a "
pass
s += next(stream)
yield (tokens.String,s)
elif stream.startswithalpha():
s=''
while stream.startswithalphanumeric():
s += next(stream)
if s in tokens.builtin_functions:
yield (tokens.BuiltinFunction,s)
elif s in tokens.builtin_keywords:
yield (tokens.Keyword,s)
elif s in tokens.builtin_constants:
yield (tokens.BuiltinConstant,s)
elif s in tokens.builtin_types:
yield (tokens.Type,s)
else:
yield (tokens.FunctionName,s)
elif stream.startswithnumeric():
s=''
# Exponent notation not (yet) supported
while stream.startswithnumeric():
s += next(stream)
if stream.startswith('.'):
s += '.'
while stream.startswithnumeric():
s += next(stream)
yield (tokens.Number,s)
elif stream.startswith('$'):
s=''
while stream.startswithalphanumeric():
s += next(stream)
yield (tokens.Variable,s)
else:
yield (tokens.BadChar,next(stream))
# print('ending php block')
else:
char = next(stream)
# print('col {0}: {1}'.format(col,char))
except StopIteration:
pass
# print('end of file')
class tokenstream:
''' Takes a filename string and returns a stream of tokens that
supports reading one token ahead '''
def __init__(self,filename):
self.filename=filename
def __iter__(self):
# character stream with readahead
self.charstream = iter(charstream(self.filename))
# token stream with no readahead
self.stream=iter(scanfile(self.charstream))
self.nexttok = None
return self
def __next__(self):
if self.nexttok:
nexttok = self.nexttok
self.nexttok = None
return nexttok
else:
return next(self.stream)
def position(self):
''' Return the filename and line number of the latest returned
(or peeked!) token'''
return '{0}:{1}'.format(self.filename,self.charstream.linenumber())
def peek(self):
''' Return the next token without consuming it, or None if
we're a the end of the file. Unlike next() itself, this never
raises StopIteration '''
try:
if not self.nexttok:
self.nexttok = next(self.stream)
# print('Peeking {0}'.format(tokens.shorttok(self.nexttok)))
except StopIteration:
return (tokens.EndOfFile,)
return self.nexttok
def skip(self,tok):
''' if the next token it is equal to tok, consume it and
return True. Otherise do nothing and return False'''
if self.peek()==tok:
next(self)
return True
else:
return False
def require(self,tok,msg=''):
''' Like skip but prints a warning if said token wasn't found. msg can detail why that particular token is needed. '''
if self.skip(tok):
return True
else:
print('{0}: WARNING, {1} expected {3}, got {2}.'.format(self.position(), tokens.prettyTok(tok), tokens.prettyTok(self.peek()),msg))
return False