-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokutil.py
409 lines (357 loc) · 15.7 KB
/
tokutil.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
# MIT License
#
# Copyright (c) 2024 Neil Webber
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Token Stream Enhancer
#
# Adds unget, peek, and mark/restore capability to any stream of "tokens"
# (really any iterable)
#
from contextlib import contextmanager
from functools import partial
from types import SimpleNamespace
import itertools
class TokStreamEnhancer:
def __init__(self, *tokstreams, lasttok=None, eoftok=None):
"""chain N tokstreams into a single stream, with pushback capability.
Optional argument lasttok will be returned as a token at the end
of the tokstreams and prior to reaching EOF condition. It is
identical to adding: iter((lasttok,)) at the end of tokstreams.
Optional argument eoftok will be returned once the end of the token
streams has been reached. If supplied, it will be returned REPEATEDLY
and no StopIteration exception will ever be raised.
If no eoftok is supplied, StopIteration will be raised once the
end of the tokstreams has been reached AND no pushbacks remain.
"""
if lasttok is not None:
tokstreams = (*tokstreams, iter((lasttok,)))
self._tokens = itertools.chain.from_iterable(tokstreams)
self._eoftok = eoftok
self._pushedback = [] # see peektok() etc
self._markedtoks = None # for unwinding tokens
self._unmarkctx = None # for unwinding tokens
def __unget_invalid_after_iter(self, *arg, **kwargs):
raise TypeError("ungettok is not legal after __iter__ usage")
def __iter__(self):
"""Using iterator protocol on TokStreamEnhancer is somewhat silly.
Nevertheless, here it is. There are two important restrictions:
1) eoftok must be None
2) ungettok can not be used.
See comments in code for details.
"""
# eoftok semantics and __iter__ protocol clash; one prevents
# StopIteration and the other requires it. If what was desired
# was for one special token to appear at the end of the iteration
# then lasttok should be used instead.
if self._eoftok is not None:
raise TypeError("cannot __iter__ with an eoftok present")
# The other restriction is: no ungettok. This is because
# the Python documentation for iterator protocol says:
# Once an iterator’s __next__() method raises StopIteration,
# it must continue to do so on subsequent calls. Implementations
# that do not obey this property are deemed broken.
self.ungettok = self.__unget_invalid_after_iter # crude; effective
return self
def __next__(self):
if self._pushedback:
return self._pushedback.pop(0)
return next(self._tokens)
# token peek/get .. everything is built on top of peektoks() which
# ensures there are at least N tokens on the _pushedback queue.
def peektoks(self, n):
"""Return a LIST of n tokens, WITHOUT consuming them."""
while len(self._pushedback) < n:
try:
t = next(self._tokens)
except StopIteration:
if self._eoftok is None:
raise
t = self._eoftok
self._pushedback.append(t)
return self._pushedback[:n]
def peektok(self):
"""Return a single token, WITHOUT consuming it."""
return self.peektoks(1)[0]
_NOTGIVEN = object()
def peekif(self, pred, /, *, eofmatch=_NOTGIVEN):
"""Return (peek) a token, if pred(token) is True, else return None.
If optional argument eofmatch is given, it is returned (regardless
of pred match) if at_eof().
"""
if eofmatch is not self._NOTGIVEN and self.at_eof():
return eofmatch
t = self.peektok()
return t if pred(t) else None
def at_eof(self):
try:
return self.peektok() is self._eoftok
except StopIteration:
return True
def gettok(self):
"""Return a single token and move to next."""
self.peektok() # guarantee at least one on pushedback
t = self._pushedback.pop(0)
if self._markedtoks is not None: # see tokmark()
self._markedtoks.append(t)
return t
def gettoks(self, n):
"""Like n calls to gettok(), returning a LIST of n tokens"""
return [self.gettok() for _ in range(n)]
def ungettok(self, tok=None, *, bulk=None):
"""Push tok back onto front of stream.
An entire list of toks can be pushed back via 'bulk'.
It is illegal to supply both tok and bulk.
"""
if bulk is None:
self._pushedback.insert(0, tok)
elif tok is None:
if bulk: # it could be zero-len
self._pushedback = bulk + self._pushedback
else:
raise TypeError("called with BOTH tok and bulk")
# tokmark is a WITH statement context manager.
# It sets a 'mark' in the token stream and automatically ungets
# tokens back to that point when the context is exited.
#
# acceptmarks() prevents that unwind for the "current" context.
#
# In the simplest, non-nested form:
# with foo.tokmark():
# t1 = foo.gettok()
# t2 = foo.gettok()
#
# This is equivalent to calling gettok ZERO times ... no tokens
# will be consumed. More precisely, they are consumed during the
# context, but are put back when the context terminates.
#
# Method acceptmarks() neutralizes the tokmark() so that all tokens
# will remain consumed, whether they were consumed before or after
# the call to acceptmark(). For example:
# with foo.tokmark():
# t1 = foo.gettok()
# t2 = foo.gettok()
# foo.acceptmarks()
# t3 = foo.gettok()
#
# This is equivalent to calling gettok() three times.
#
# Usage of mark/accept can be nested, in which case an explicit context
# must be provided, and acceptmarks invoked from that context:
# with foo.tokmark() as ctx:
# t1 = foo.gettok()
# with foo.tokmark() as ctx2:
# t2 = foo.gettok()
# ctx2.acceptmarks()
# t3 = foo.gettok()
# t4 = foo.gettok()
#
# This will cause t3 to be the same token AFTER t2, because of
# the ctx2.acceptmarks(). However, t4 will be the same token as t1,
# (and the next two tokens will be the same as t2, t3, respectively)
# because the outer context was not accepted.
@contextmanager
def tokmark(self):
ctx = SimpleNamespace()
ctx.acceptmarks = partial(self.acceptmarks, ctx)
ctx.accepted = False
ctx.prevmarked, self._markedtoks = self._markedtoks, []
prevctx, self._unmarkctx = self._unmarkctx, ctx
try:
yield ctx
finally:
if ctx.accepted:
# if there is a nested context these tokens still need
# to be added to THAT one
if ctx.prevmarked is not None:
ctx.prevmarked += self._markedtoks
else:
self.ungettok(bulk=self._markedtoks)
self._markedtoks = ctx.prevmarked
self._unmarkctx = prevctx
def acceptmarks(self, ctx=None):
"""Disable (i.e., no-op) the unwind of current tokmark() context."""
if ctx is None:
ctx = self._unmarkctx
ctx.accepted = True
if __name__ == "__main__":
import unittest
class TestMethods(unittest.TestCase):
def testsimple(self):
t = TokStreamEnhancer(iter((1, 2, 3)))
self.assertEqual(t.gettok(), 1)
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
with self.assertRaises(StopIteration):
t.gettok()
def testN(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
self.assertEqual(t.gettok(), 1)
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
self.assertEqual(t.gettok(), 4)
self.assertEqual(t.gettok(), 5)
with self.assertRaises(StopIteration):
t.gettok()
def testEOFtok(self):
t = TokStreamEnhancer(iter((1, 2)), eoftok=99)
self.assertEqual(t.gettok(), 1)
self.assertEqual(t.gettok(), 2)
self.assertTrue(t.at_eof())
for i in range(10): # arbitrary, point is > 1
self.assertEqual(t.gettok(), 99)
self.assertTrue(t.at_eof())
def testLASTtok(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), lasttok=99)
self.assertEqual(t.gettok(), 1)
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 99)
with self.assertRaises(StopIteration):
t.gettok()
def testLASTandEOFtok(self):
t = TokStreamEnhancer(iter((1, 2)), lasttok=17, eoftok=99)
self.assertEqual(t.gettok(), 1)
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 17)
self.assertTrue(t.at_eof())
for i in range(10): # arbitrary, point is > 1
self.assertEqual(t.gettok(), 99)
def test_peek(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
for i in range(5+1):
self.assertEqual(t.peektoks(i), list(range(1, i+1)))
self.assertEqual(t.gettok(), 1)
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
self.assertEqual(t.gettok(), 4)
self.assertEqual(t.gettok(), 5)
with self.assertRaises(StopIteration):
t.gettok()
def test_peekpastEOF(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
for i in range(5+1+4):
try:
toks = t.peektoks(i)
self.assertEqual(toks, list(range(1, i+1)))
except StopIteration:
self.assertTrue(i > 5)
def test_peekpastEOFtok(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)),
eoftok=99)
for i in range(5+1+4):
toks = t.peektoks(i)
if i <= 5:
self.assertEqual(toks, list(range(1, i+1)))
else:
self.assertEqual(toks, list(range(1, 6)) + [99] * (i - 5))
def test_peekif(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
self.assertEqual(t.peekif(lambda t: t == 2), None)
self.assertEqual(t.gettok(), 1)
self.assertEqual(t.peekif(lambda t: t == 2), 2)
def test_mark(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
self.assertEqual(t.gettok(), 1)
with t.tokmark() as ctx:
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
self.assertEqual(t.gettok(), 4)
self.assertEqual(t.gettok(), 5)
self.assertTrue(t.at_eof())
def test_mark_accept(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
self.assertEqual(t.gettok(), 1)
with t.tokmark() as ctx:
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
ctx.acceptmarks()
self.assertEqual(t.gettok(), 4)
self.assertEqual(t.gettok(), 5)
self.assertTrue(t.at_eof())
def test_mark_accept_nested(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
self.assertEqual(t.gettok(), 1)
with t.tokmark() as ctx:
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
with t.tokmark() as ctx2:
self.assertEqual(t.gettok(), 4)
self.assertEqual(t.gettok(), 5)
ctx.acceptmarks()
self.assertEqual(t.gettok(), 4)
self.assertEqual(t.gettok(), 5)
self.assertTrue(t.at_eof())
def test_mark_accept_nested2(self):
t = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
self.assertEqual(t.gettok(), 1)
with t.tokmark() as ctx:
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
with t.tokmark() as ctx2:
self.assertEqual(t.gettok(), 4)
ctx2.acceptmarks()
self.assertEqual(t.gettok(), 2)
self.assertEqual(t.gettok(), 3)
self.assertEqual(t.gettok(), 4)
self.assertEqual(t.gettok(), 5)
self.assertTrue(t.at_eof())
def test_mark_example(self):
# the test case form the comments in tokmark()/accept:
foo = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
with foo.tokmark() as ctx:
t1 = foo.gettok()
self.assertEqual(t1, 1)
with foo.tokmark() as ctx2:
t2 = foo.gettok()
self.assertEqual(t2, 2)
ctx2.acceptmarks()
t3 = foo.gettok()
self.assertEqual(t3, 3)
t4 = foo.gettok()
self.assertEqual(t4, t1)
self.assertEqual(foo.gettok(), t2)
self.assertEqual(foo.gettok(), t3)
def test_mark_example2(self):
# the same test but using implicit contexts
foo = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
with foo.tokmark():
t1 = foo.gettok()
self.assertEqual(t1, 1)
with foo.tokmark():
t2 = foo.gettok()
self.assertEqual(t2, 2)
foo.acceptmarks()
t3 = foo.gettok()
self.assertEqual(t3, 3)
t4 = foo.gettok()
self.assertEqual(t4, t1)
self.assertEqual(foo.gettok(), t2)
self.assertEqual(foo.gettok(), t3)
def test_iter(self):
foo = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
for i, t in enumerate(foo):
self.assertEqual(i+1, t)
def test_iter_unget(self):
foo = TokStreamEnhancer(iter((1,)), iter((2,)), iter((3, 4, 5)))
for t in foo:
with self.assertRaises(TypeError):
foo.ungettok(t)
unittest.main()