Repository navigation
Expand file tree
/
Copy pathstream.py
More file actions
99 lines (80 loc) · 2.75 KB
/
Copy pathstream.py
File metadata and controls
99 lines (80 loc) · 2.75 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
# noqa: D100
from __future__ import annotations
from collections import deque
from typing import Deque
from typing import Iterator
from .exceptions import JSONPathSyntaxError
from .token import TOKEN_EOF
from .token import Token
# ruff: noqa: D102
class TokenStream:
"""Step through or iterate a stream of tokens."""
def __init__(self, token_iter: Iterator[Token]):
self.iter = token_iter
self._pushed: Deque[Token] = deque()
self.current = Token("", "", -1, "")
next(self)
class TokenStreamIterator:
"""An iterable token stream."""
def __init__(self, stream: TokenStream):
self.stream = stream
def __iter__(self) -> Iterator[Token]:
return self
def __next__(self) -> Token:
tok = self.stream.current
if tok.kind is TOKEN_EOF:
self.stream.close()
raise StopIteration
next(self.stream)
return tok
def __iter__(self) -> Iterator[Token]:
return self.TokenStreamIterator(self)
def __next__(self) -> Token:
tok = self.current
if self._pushed:
self.current = self._pushed.popleft()
elif self.current.kind is not TOKEN_EOF:
try:
self.current = next(self.iter)
except StopIteration:
self.close()
return tok
def __str__(self) -> str: # pragma: no cover
return f"current: {self.current}\nnext: {self.peek}"
def next_token(self) -> Token:
"""Return the next token from the stream."""
return next(self)
@property
def peek(self) -> Token:
"""Look at the next token."""
current = next(self)
result = self.current
self.push(current)
return result
def push(self, tok: Token) -> None:
"""Push a token back to the stream."""
self._pushed.append(self.current)
self.current = tok
def close(self) -> None:
"""Close the stream."""
self.current = Token(TOKEN_EOF, "", -1, "")
def expect(self, *typ: str) -> None:
if self.current.kind not in typ:
if len(typ) == 1:
_typ = repr(typ[0])
else:
_typ = f"one of {typ!r}"
raise JSONPathSyntaxError(
f"expected {_typ}, found {self.current.kind!r}",
token=self.current,
)
def expect_peek(self, *typ: str) -> None:
if self.peek.kind not in typ:
if len(typ) == 1:
_typ = repr(typ[0])
else:
_typ = f"one of {typ!r}"
raise JSONPathSyntaxError(
f"expected {_typ}, found {self.peek.kind!r}",
token=self.peek,
)