-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparser_types.py
More file actions
310 lines (239 loc) · 9.78 KB
/
parser_types.py
File metadata and controls
310 lines (239 loc) · 9.78 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
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
import abc
import json
import re
import typing as t
from . import nodes
from .abc import Node
from .exceptions import ParserException
from .util import get, tokenize
class ParserType(metaclass=abc.ABCMeta):
@abc.abstractmethod
def parse(self, parts: t.Iterator[str]) -> Node:
raise NotImplementedError
class Any(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.RawNode:
return nodes.RawNode(get(parts))
class Block(ParserType):
namespace = re.compile(
r'(#?)([0-9a-z_.-]+:)?([0-9a-z_./-]+)(\[.*])?({.*})?'
)
def parse(self, parts: t.Iterator[str]) -> nodes.BlockNode:
arg = get(parts)
match = self.namespace.fullmatch(arg)
if match is None:
raise ParserException(
f'expected valid block, not {arg!r}'
)
is_tag, namespace, name, blockstates, datatags = match.groups()
if namespace is not None:
namespace = namespace[:-1] # remove ':'
return nodes.BlockNode(bool(is_tag), namespace, name, blockstates,
datatags)
class Coordinate(ParserType):
@classmethod
def parse(cls, parts: t.Iterator[str]) -> nodes.CoordinateNode:
arg = get(parts)
try:
if arg.startswith('~'):
return nodes.CoordinateNode(
float(arg[1:]) if len(arg) > 1 else 0, relative=True
)
elif arg.startswith('^'):
return nodes.CoordinateNode(
float(arg[1:]) if len(arg) > 1 else 0, local=True
)
return nodes.CoordinateNode(float(arg))
except ValueError:
raise ParserException(f'invalid coordinate: {arg!r}')
class GreedyAny(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.RawNode:
# return nodes.RawNode(' '.join(parts))
seq = []
for x in parts:
seq.append(x)
if not seq:
raise ParserException('too few arguments')
return nodes.RawNode(' '.join(seq))
class Double(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.DoubleNode:
arg = get(parts)
try:
value = float(arg)
except ValueError:
raise ParserException(f'expected double, not {arg!r}')
else:
return nodes.DoubleNode(value)
class Entity(ParserType):
valid_usernames = re.compile(r'[a-zA-Z0-9_]{3,16}')
def parse(self, parts: t.Iterator[str]) -> nodes.EntityNode:
arg = get(parts)
selector = arg.split('[')[0]
arguments = []
if selector.startswith('@'):
if selector[1:] not in 'aeprs':
raise ParserException(f'invalid selector: {arg!r}')
else:
if (not self.valid_usernames.fullmatch(selector)
and not UUID.uuid.fullmatch(selector)):
# may need some adjusting for chinese people
raise ParserException(f'invalid username: {arg!r}')
if '[' in arg: # we got arguments
if not arg.endswith(']'):
raise ParserException(
f'expected \']\' at the end of valid entity: {arg!r}'
)
args = arg[len(selector) + 1:-1]
arguments.extend(
nodes.EntitySelectorConditionNode(*tokenize(name_value, '='))
for name_value in tokenize(args, ',')
)
return nodes.EntityNode(selector, arguments)
class Function(ParserType):
namespace = re.compile(r'(#?)([0-9a-z_.-]+):([0-9a-z_./-]+)')
def parse(self, parts: t.Iterator[str]) \
-> nodes.FunctionNode:
arg = get(parts)
match = self.namespace.fullmatch(arg)
if match is None:
raise ParserException(
f'expected valid function, not {arg!r}'
)
is_tag, namespace, name = match.groups()
return nodes.FunctionNode(bool(is_tag), namespace, name)
class IPAddress(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.RawNode:
arg = get(parts)
ip_parts = arg.split('.')
if len(ip_parts) != 4:
raise ParserException('malformed ip address')
try:
ip_parts = [int(x) for x in ip_parts]
except ValueError:
raise ParserException('non number in ip address')
if min(ip_parts) < 0 or max(ip_parts) > 255:
raise ParserException('invalid ip address')
return nodes.RawNode(arg)
class Integer(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.IntegerNode:
arg = get(parts)
try:
value = int(arg)
except ValueError:
raise ParserException(f'expected integer, not {arg!r}')
else:
return nodes.IntegerNode(value)
class Item(ParserType):
namespace = re.compile(r'(#?)([0-9a-z_.-]+:)?([0-9a-z_./-]+)({.*})?')
def parse(self, parts: t.Iterator[str]) -> nodes.ItemNode:
arg = get(parts)
match = self.namespace.fullmatch(arg)
if match is None:
raise ParserException(
f'expected valid item, not {arg!r}'
)
is_tag, namespace, name, datatags = match.groups()
if namespace is not None:
namespace = namespace[:-1] # remove ':'
return nodes.ItemNode(bool(is_tag), namespace, name, datatags)
class JSON(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.JSONNode:
arg = get(parts)
try:
object = json.loads(arg)
except json.JSONDecodeError:
raise ParserException(f'expected valid json, not {arg!r}')
return nodes.JSONNode(object)
class Literal(ParserType):
def __init__(self, value: str):
self._value = value
def parse(self, parts: t.Iterator[str]) -> nodes.RawNode:
arg = get(parts)
if arg != self._value:
raise ParserException(f'expected {self._value!r}, not {arg!r}')
return nodes.RawNode(arg)
class NamespaceID(ParserType):
namespace = re.compile(r'([0-9a-z_.-]+:)?([0-9a-z_./-]+)')
def parse(self, parts: t.Iterator[str]) \
-> nodes.NamespaceIDNode:
arg = get(parts)
match = self.namespace.fullmatch(arg)
if match is None:
raise ParserException(
f'expected valid namespace identifier, not {arg!r}'
)
namespace, name = match.groups()
if namespace is not None:
namespace = namespace[:-1] # remove ':'
return nodes.NamespaceIDNode(namespace, name)
class Objective(ParserType):
objective = re.compile(r'[a-zA-Z0-9_.+-]{,16}')
def parse(self, parts: t.Iterator[str]) -> nodes.RawNode:
arg = get(parts)
match = self.objective.fullmatch(arg)
if match is None:
raise ParserException(f'expected valid objective, not {arg!r}')
return nodes.RawNode(arg)
class Particle(ParserType):
namespace = re.compile(r'([0-9a-z_.-]+:)?([0-9a-z_./-]+)')
def parse(self, parts: t.Iterator[str]) -> nodes.ParticleNode:
arg = get(parts)
match = self.namespace.fullmatch(arg)
if match is None:
raise ParserException(
f'expected valid particle, not {arg!r}'
)
namespace, name = match.groups()
if namespace is not None:
namespace = namespace[:-1] # remove ':'
arguments = None
if namespace is None or namespace == 'minecraft':
if name == 'dust':
arguments = tuple(nodes.DoubleNode(float(x))
for x in get(parts, 4))
elif name in ('block', 'falling_dust'):
match = Block.namespace.fullmatch(get(parts))
arguments = (nodes.BlockNode(*match.groups()),)
elif name == 'item':
match = NamespaceID.namespace.fullmatch(get(parts))
arguments = (nodes.NamespaceIDNode(*match.groups()),)
elif name == 'vibration':
arguments = (Position().parse(parts), Position().parse(parts),
Integer().parse(parts))
elif name == 'dust_color_transition':
arguments = tuple(nodes.DoubleNode(float(x))
for x in get(parts, 7))
return nodes.ParticleNode(namespace, name, arguments)
class Position(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.PositionNode:
return nodes.PositionNode(Coordinate.parse(parts),
Coordinate.parse(parts),
Coordinate.parse(parts))
class Position2d(ParserType):
def parse(self, parts: t.Iterator[str]) \
-> nodes.Position2dNode:
return nodes.Position2dNode(Coordinate.parse(parts),
Coordinate.parse(parts))
class Rotation(ParserType):
def parse(self, parts: t.Iterator[str]) -> nodes.RotationNode:
return nodes.RotationNode(Coordinate.parse(parts),
Coordinate.parse(parts))
class ScoreboardEntity(Entity):
valid_usernames = re.compile(r'.+')
class Union(ParserType):
def __init__(self, *options):
self._options = options
def parse(self, parts: t.Iterator[str]) -> nodes.RawNode:
arg = get(parts)
if arg not in self._options:
raise ParserException(
f'expected any of {self._options!r}, not {arg!r}'
)
return nodes.RawNode(arg)
class UUID(ParserType):
uuid = re.compile('-'.join([r'[0-9a-fA-F]+'] * 5))
def parse(self, parts: t.Iterator[str]) -> nodes.RawNode:
arg = get(parts)
match = self.uuid.fullmatch(arg)
if match is None:
raise ParserException(f'expected valid uuid, not {arg!r}')
return nodes.RawNode(arg)