-
Notifications
You must be signed in to change notification settings - Fork 268
/
lex.py
356 lines (309 loc) · 10 KB
/
lex.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
# -*- coding: utf-8 -*-
from __future__ import print_function
import collections,string
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class Lexer(object):
"""
Simple Lexer base class. Provides basic lexer framework and
helper functionality (read/peek/pushback etc)
Each state is implemented using a method (lexXXXX) which should
match a single token and return a (token,lexYYYY) tuple, with lexYYYY
representing the next state. If token is None this is not emitted
and if lexYYYY is None or the lexer reaches the end of the
input stream the lexer exits.
The 'parse' method returns a generator that will return tokens
(the class also acts as an iterator)
The default start state is 'lexStart'
Input can either be a string/bytes or file object.
The approach is based loosely on Rob Pike's Go lexer presentation
(using generators rather than channels).
>>> p = Lexer("a bcd efgh")
>>> p.read()
'a'
>>> p.read()
' '
>>> p.peek(3)
'bcd'
>>> p.read(5)
'bcd e'
>>> p.pushback('e')
>>> p.read(4)
'efgh'
"""
escape_chars = '\\'
escape = {'n':'\n','t':'\t','r':'\r'}
def __init__(self,f,debug=False):
if hasattr(f,'read'):
self.f = f
elif type(f) == str:
self.f = StringIO(f)
elif type(f) == bytes:
self.f = StringIO(f.decode())
else:
raise ValueError("Invalid input")
self.debug = debug
self.q = collections.deque()
self.state = self.lexStart
self.escaped = False
self.eof = False
def __iter__(self):
return self.parse()
def next_token(self):
if self.debug:
print("STATE",self.state)
(tok,self.state) = self.state()
return tok
def parse(self):
while self.state is not None and not self.eof:
tok = self.next_token()
if tok:
yield tok
def read(self,n=1):
s = ""
while self.q and n > 0:
s += self.q.popleft()
n -= 1
s += self.f.read(n)
if s == '':
self.eof = True
if self.debug:
print("Read: >%s<" % repr(s))
return s
def peek(self,n=1):
s = ""
i = 0
while len(self.q) > i and n > 0:
s += self.q[i]
i += 1
n -= 1
r = self.f.read(n)
if n > 0 and r == '':
self.eof = True
self.q.extend(r)
if self.debug:
print("Peek : >%s<" % repr(s + r))
return s + r
def pushback(self,s):
p = collections.deque(s)
p.extend(self.q)
self.q = p
def readescaped(self):
c = self.read(1)
if c in self.escape_chars:
self.escaped = True
n = self.peek(3)
if n.isdigit():
n = self.read(3)
if self.debug:
print("Escape: >%s<" % n)
return chr(int(n,8))
elif n[0] in 'x':
x = self.read(3)
if self.debug:
print("Escape: >%s<" % x)
return chr(int(x[1:],16))
else:
c = self.read(1)
if self.debug:
print("Escape: >%s<" % c)
return self.escape.get(c,c)
else:
self.escaped = False
return c
def lexStart(self):
return (None,None)
class WordLexer(Lexer):
"""
Example lexer which will split input stream into words (respecting
quotes)
To emit SPACE tokens: self.spacetok = ('SPACE',None)
To emit NL tokens: self.nltok = ('NL',None)
>>> l = WordLexer(r'abc "def\100\x3d\. ghi" jkl')
>>> list(l)
[('ATOM', 'abc'), ('ATOM', 'def@=. ghi'), ('ATOM', 'jkl')]
>>> l = WordLexer(r"1 '2 3 4' 5")
>>> list(l)
[('ATOM', '1'), ('ATOM', '2 3 4'), ('ATOM', '5')]
>>> l = WordLexer("abc# a comment")
>>> list(l)
[('ATOM', 'abc'), ('COMMENT', 'a comment')]
"""
wordchars = set(string.ascii_letters) | set(string.digits) | \
set(string.punctuation)
quotechars = set('"\'')
commentchars = set('#')
spacechars = set(' \t\x0b\x0c')
nlchars = set('\r\n')
spacetok = None
nltok = None
def lexStart(self):
return (None,self.lexSpace)
def lexSpace(self):
s = []
if self.spacetok:
tok = lambda n : (self.spacetok,n) if s else (None,n)
else:
tok = lambda n : (None,n)
while not self.eof:
c = self.peek()
if c in self.spacechars:
s.append(self.read())
elif c in self.nlchars:
return tok(self.lexNL)
elif c in self.commentchars:
return tok(self.lexComment)
elif c in self.quotechars:
return tok(self.lexQuote)
elif c in self.wordchars:
return tok(self.lexWord)
return (self.spacetok,self.lexWord)
elif c:
raise ValueError("Invalid input [%d]: %s" % (
self.f.tell(),c))
return (None,None)
def lexNL(self):
while True:
c = self.read()
if c not in self.nlchars:
self.pushback(c)
return (self.nltok,self.lexSpace)
def lexComment(self):
s = []
tok = lambda n : (('COMMENT',''.join(s)),n) if s else (None,n)
start = False
_ = self.read()
while not self.eof:
c = self.read()
if c == '\n':
self.pushback(c)
return tok(self.lexNL)
elif start or c not in string.whitespace:
start = True
s.append(c)
return tok(None)
def lexWord(self):
s = []
tok = lambda n : (('ATOM',''.join(s)),n) if s else (None,n)
while not self.eof:
c = self.peek()
if c == '"':
return tok(self.lexQuote)
elif c in self.commentchars:
return tok(self.lexComment)
elif c.isspace():
return tok(self.lexSpace)
elif c in self.wordchars:
s.append(self.read())
elif c:
raise ValueError('Invalid input [%d]: %s' % (
self.f.tell(),c))
return tok(None)
def lexQuote(self):
s = []
tok = lambda n : (('ATOM',''.join(s)),n)
q = self.read(1)
while not self.eof:
c = self.readescaped()
if c == q and not self.escaped:
break
else:
s.append(c)
return tok(self.lexSpace)
class RandomLexer(Lexer):
"""
Test lexing from infinite stream.
Extract strings of letters/numbers from /dev/urandom
>>> import itertools,sys
>>> if sys.version[0] == '2':
... f = open("/dev/urandom")
... else:
... f = open("/dev/urandom",encoding="ascii",errors="replace")
>>> r = RandomLexer(f)
>>> i = iter(r)
>>> len(list(itertools.islice(i,10)))
10
"""
minalpha = 4
mindigits = 3
def lexStart(self):
return (None,self.lexRandom)
def lexRandom(self):
n = 0
c = self.peek(1)
while not self.eof:
if c.isalpha():
return (None,self.lexAlpha)
elif c.isdigit():
return (None,self.lexDigits)
else:
n += 1
_ = self.read(1)
c = self.peek(1)
return (None,None)
def lexDigits(self):
s = []
c = self.read(1)
while c.isdigit():
s.append(c)
c = self.read(1)
self.pushback(c)
if len(s) >= self.mindigits:
return (('NUMBER',"".join(s)),self.lexRandom)
else:
return (None,self.lexRandom)
def lexAlpha(self):
s = []
c = self.read(1)
while c.isalpha():
s.append(c)
c = self.read(1)
self.pushback(c)
if len(s) >= self.minalpha:
return (('STRING',"".join(s)),self.lexRandom)
else:
return (None,self.lexRandom)
if __name__ == '__main__':
import argparse,doctest,sys
p = argparse.ArgumentParser(description="Lex Tester")
p.add_argument("--lex","-l",action='store_true',default=False,
help="Lex input (stdin)")
p.add_argument("--nl",action='store_true',default=False,
help="Output NL tokens")
p.add_argument("--space",action='store_true',default=False,
help="Output Whitespace tokens")
p.add_argument("--wordchars",help="Wordchars")
p.add_argument("--quotechars",help="Quotechars")
p.add_argument("--commentchars",help="Commentchars")
p.add_argument("--spacechars",help="Spacechars")
p.add_argument("--nlchars",help="NLchars")
args = p.parse_args()
if args.lex:
l = WordLexer(sys.stdin)
if args.wordchars:
l.wordchars = set(args.wordchars)
if args.quotechars:
l.quotechars = set(args.quotechars)
if args.commentchars:
l.commentchars = set(args.commentchars)
if args.spacechars:
l.spacechars = set(args.spacechars)
if args.nlchars:
l.nlchars = set(args.nlchars)
if args.space:
l.spacetok = ('SPACE',)
if args.nl:
l.nltok = ('NL',)
for tok in l:
print(tok)
else:
try:
# Test if we have /dev/urandom
open("/dev/urandom")
doctest.testmod()
except IOError:
# Don't run stream test
doctest.run_docstring_examples(Lexer, globals())
doctest.run_docstring_examples(WordLexer, globals())