-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_code.py
More file actions
638 lines (463 loc) · 18.9 KB
/
main_code.py
File metadata and controls
638 lines (463 loc) · 18.9 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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import re
import sys
from dataclasses import dataclass
from typing import Literal, TypeVar
from collections.abc import Callable
if sys.version_info < (3, 10):
from typing_extensions import ParamSpec
else:
from typing import ParamSpec
_P = ParamSpec("_P")
_T = TypeVar("_T")
Signature = ["match", "value"]
def toBuffer(value: str | int):
if isinstance(value, str):
res = value
else:
assert 0 <= value and value <= 0xFF
res = [value]
assert len(res) >= 1
return res
# TODO Add text validataion...
def validate_text(init: Callable[_P, _T]) -> Callable[_P, _T]:
def is_valid(args, kwargs):
if kwargs.get("field"):
field = kwargs["field"]
if re.search(r"[//\s\\]+", field):
raise TypeError(
f'Can\'t access internal field because the field: "{field}" conatins invalid characters'
)
return init(args, kwargs)
return is_valid
class Code:
def __init__(
self, signature: Literal["match", "value"], name: str, independent: bool = False
) -> None:
assert signature in Signature, "Invalid signature %s" % signature
# Added in 0.2.1 this label marks that a function is user-made
# examples of this would be Value and _Match nodes
self.is_independent = independent
self.signature = signature
self.name = name
def __hash__(self):
return hash(self.signature + self.name)
class Field(Code):
def __init__(
self, signature: Literal["match", "value"], name: str, field: str
) -> None:
self.field = field
# if re.search(r"[//\s\\]+",field):
# raise TypeError(f"Can\'t access internal field from user code because the field: {name} conatins invalid characters")
super().__init__(signature, name + "_" + field)
class FieldValue(Field):
def __init__(
self, signature: Literal["match", "value"], name: str, field: str, value: int
) -> None:
self.value = value
super().__init__(signature, name, field)
class And(FieldValue):
def __init__(self, field: str, value: int) -> None:
super().__init__("match", "and", field, value)
class IsEqual(FieldValue):
def __init__(self, field: str, value: int) -> None:
super().__init__("match", "is_equal", field, value)
OperatorsMap = {"<": "lt", ">": "gt", ">=": "ge", "<=": "le"}
class Operator(FieldValue):
"""An Operator such as `>, <, >=, <=` made for dealing with
properties with infinate sizes"""
def __init__(self, op: str, field: str, value: int) -> None:
if name := OperatorsMap.get(op):
super().__init__("match", name, field, value)
# Make sure our operator can be remebered for later...
self.op = op
else:
raise NotImplementedError(
f"operator {op} not implemented or doesnt exist yet"
)
class Load(Field):
def __init__(self, field: str) -> None:
super().__init__("match", "load", field)
class _Match(Code):
"""Refers to the Code's Match Not the Node's Match"""
def __init__(self, name: str) -> None:
super().__init__("match", name, independent=True)
@dataclass
class IMulAddOptions:
base: int
max: int
signed: bool = False
class MulAdd(Field):
def __init__(self, field: str, base: int, max: int, signed: bool = False) -> None:
self.options = IMulAddOptions(base, max, signed)
super().__init__("value", "mul_add", field)
class Or(FieldValue):
def __init__(self, field: str, value: int) -> None:
super().__init__("match", "or", field, value)
# class Span(Match):
# def __init__(self, name: str) -> None:
# super().__init__(name)
class Store(Field):
def __init__(self, field: str) -> None:
self.field = field
super().__init__("value", "store", field)
class Test(FieldValue):
def __init__(self, field: str, value: int) -> None:
super().__init__("match", "test", field, value)
class Update(FieldValue):
def __init__(self, field: str, value: int) -> None:
super().__init__("match", "update", field, value)
class Value(Code):
def __init__(self, name: str) -> None:
super().__init__("value", name, is_independent=True)
# Nodes...
class Node:
def __init__(self, name: str) -> None:
self.name = name
self.otherwiseEdge: Edge | None = None
self.privEdges: list[Edge] = []
def key(self):
"""reversed for sorting to prevent python from creating artificial randomness"""
return self.name
def __hash__(self) -> int:
return hash(self.name)
def otherwise(self, node: "Node"):
if self.otherwiseEdge:
raise TypeError("Node Already has an 'otherwise' or 'skipto'")
self.otherwiseEdge = Edge(node, True, None, None)
return self
def skipTo(self, node: "Node"):
if self.otherwiseEdge:
raise TypeError("Node Already has an 'otherwise' or 'skipto'")
self.otherwiseEdge = Edge(node, False, None, None)
return self
def getOtherwiseEdge(self):
return self.otherwiseEdge
def getEdges(self):
"""Returns non if object is empty"""
return None if self.privEdges == [] else self.privEdges
def getAllEdges(self):
r"Get list of all edges (including otherwise, if present)"
res = self.privEdges
if not self.otherwiseEdge:
return res
else:
# Concate DO NOT ADD TO RES!!!!
return res + [self.otherwiseEdge]
def __iter__(self):
if self.privEdges != []:
for e in self.privEdges:
yield e
def addEdge(self, edge: "Edge"):
assert isinstance(edge.key, (int, str)) or edge.key
if len(self.privEdges) > 0:
assert edge.key not in [e.key for e in self.privEdges]
self.privEdges.insert(0, edge)
# TODO Add strict type checking to \"Pause.__init__\"" parameters to prevent the
# bypassing arbtrary values
class Pause(Node):
def __init__(self, code: int, reason: str) -> None:
self.code = code
self.reason = reason
super().__init__("pause")
def skipTo(self, node: "Node"):
"""`WARNING!` `Pause.skipTo()` IS NOT SUPPORTED AND WILL IMMEDIATELY THROW AN `Execption` IF YOU DO IT"""
raise Exception("Not supported in Pause Class, please use '.otherwise'")
class Comsume(Node):
def __init__(self, field: str) -> None:
self.field = field
super().__init__("consume_" + field)
class Error(Node):
def __init__(self, code: int, reason: str) -> None:
super().__init__("error")
# print(code)
assert isinstance(code, int), "code is supposed to be an int not %s" % (
type(code).__name__
)
self.code = code
self.reason = reason
def otherwise(self, node: "Node"):
raise TypeError("Not Supported")
def skipTo(self, node: "Node"):
raise TypeError("Not Supported")
class Invoke(Node):
def __init__(self, code: Code, IInvokeMap: dict[int, Node]) -> None:
self.code = code
super().__init__("invoke_" + code.name)
for numKey, targetNode in IInvokeMap.items():
if isinstance(numKey, int) and targetNode is None:
raise TypeError(
"Invoke's map keys must be integers and values must not be left blank!"
)
self.addEdge(Edge(targetNode, True, numKey, None))
# Not in llparse node-js (yet) But I wanted to implement
# this into my version since I am making a very important
# http2 frame parser
# SEE: https://github.com/nodejs/llparse-frontend/pull/1
def build_name(field: str, bits: int, signed: bool, little_endian: bool) -> str:
result = f"{field}_{'int' if signed else 'uint'}_{bits * 8}"
if bits > 1:
return result + ("_le" if little_endian else "be")
else:
return result
class Int(Node):
"""Used for parsing bytes via unpacking"""
def __init__(
self, field: str, bits: int, signed: bool, little_endian: bool
) -> None:
"""
:param field: State's property name
:param bits: Number of bits to use
:param signed: Number is signed
:param little_endian: true if le, false if be
"""
if bits < 0:
raise ValueError("bits should be a positive integer")
self.field = field
self.bits = bits
self.signed = signed
self.little_endian = little_endian
super().__init__(build_name(field, bits, signed, little_endian))
def otherwise(self, node):
"""WARNING, otherwise is skipped as it can cause unwanted problems when parsing integers.
Use skip_to or skipTo instead."""
raise TypeError("Int nodes do not support the use of `otherwise` use skipTo instead.")
# Multiple character skipping
# This is meant to lazily say "node" -> skipto(node) as many times as needed.
# Without needing to use a specified field value. Useful with spans and protocols
# that only need to collect based on a given size.
class LengthConsume(Node):
"""unlike `Consume` which requires a field, this only requires a length to be provided
allowing for optimized advancments in the parser's overall skipping capabilities"""
def __init__(self, length: int) -> None:
super().__init__(f"length_consume_{length}_bits")
self.length = length
# -- Transfroms --
TransformName = ["to_lower_unsafe", "to_lower"]
class Transform:
def __init__(self, name: str) -> None:
assert name in TransformName
self.name = name
class ToLower(Transform):
def __init__(self) -> None:
super().__init__("to_lower")
class ToLowerUnsafe(Transform):
def __init__(self) -> None:
super().__init__("to_lower_unsafe")
class TransfromCreator:
"""API For Character transformations used in::
p.node().transform(...)"""
def toLowerUnsafe(self):
return ToLowerUnsafe()
def toLower(self):
return ToLower()
# def toBuffer(value:Union[int,str,bytes]) -> bytes:
# """Returns a bytes to use when making switch cases in C..."""
# if isinstance(value,bytes):
# res = value
# elif isinstance(value,str):
# res = value.encode("utf-8","surrogateescape")
# else:
# if not (0 <= value and value <= 0xff):
# raise BufferError("Invalid byte value")
# res = chr(value).encode("utf-8","surrogateescape")
# if len(res) >= 1:
# raise AssertionError("Invalid key length")
# return res
MatchSingleValue = TypeVar("MatchSingleValue", str, int, bytes)
class Edge:
def __init__(
self,
node: Node,
noAdvance: bool,
key: int | str | None,
value: int | None,
) -> None:
self.node = node
self.noAdvance = noAdvance
self.key = key.encode() if isinstance(key, str) else key
self.value = value
# Validation...
if isinstance(node, Invoke):
# NOTE In python 0 is seen as none so simply checking for it is not an option!
# in llparse This bould be is it's equvilent of "if (value === undefined) {""
if (not isinstance(value, int)) and value is None:
if node.code.signature != "match":
raise TypeError(
f"Invalid invoke code signature : {node.code.signature} is not match"
)
elif node.code.signature != "value":
raise TypeError(
f"Invalid invoke code signature : {node.code.signature} is not value"
)
elif noAdvance:
if key and not isinstance(key, int) and len(key) != 1:
raise TypeError("Only 1-char keys are allowed in 'noAdvance' edges")
else:
# print(node)
if not isinstance(node, Node):
raise TypeError(
f"Attempted to pass value to non-Invoke node as :{type(node)}"
)
def __hash__(self) -> int:
return hash(self.node.name)
# Very Big Function but it works....
@staticmethod
def compare(a: "Edge", b: "Edge"):
return a.key == b.key
# This is where the fun begins...
class Match(Node):
"""This node matches characters/sequences and forwards the execution according
to matched character with optional attached value (See `.select()`)"""
def __init__(self, name: str) -> None:
super().__init__(name)
self.transformFn: Transform | None = None
def transform(self, transformFn: Transform):
self.transformFn = transformFn
return self
def match(self, value: str | int | list[int] | list[str], next: Node):
"""
Match sequence/character and forward execution to `next` on success,
consuming matched bytes of the input.
No value is attached on such execution forwarding, and the target node
**must not** be an `Invoke` node with a callback expecting the value.
Parameters
----------
- `value` Sequence/character to be matched
- `next` Target node to be executed on success.
"""
# if isinstance(value,str):
# value = value.encode("utf-8")
if isinstance(value, list) and len(value) > 1:
for i in value:
self.match(i.encode("utf-8") if isinstance(i, str) else i, next)
return self
edge = Edge(next, False, value, None)
self.addEdge(edge)
return self
def peek(self, value: str | int | list[str | int], next: Node):
"""Match character and forward execution to `next` on success
without consuming one byte of the input.
No value is attached on such execution forwarding, and the target node
must not be an `Invoke` with a callback expecting the value.
Parameters
----------
- `value` Character to be matched
- `next` Target node to be executed on success."""
if isinstance(value, list):
for i in value:
self.peek(i, next)
return self
if (isinstance(value, str)) and (len(value) != 1):
raise AssertionError(
".peek() accepts only singular character keys "
+ f"perhaps you meant to say : {value.split()}"
if isinstance(str, value)
else ""
)
edge = Edge(next, True, value, None)
self.addEdge(edge)
return self
# You may be asking why I'm not using Other types of Errors why assertion errors when there is not assert?
# It's beacuse it wanted to stay close to the orginal llparse library for better troubleshooting and error diagnosis - Vizonex
def select(
self,
keyOrDict: int | str | dict[str, int],
valueOrNext: int | Node | None = None,
next: Node | None = None,
):
"""Match character/sequence and forward execution to `next` on success
consumed matched bytes of the input.
Value is attached on such execution forwarding, and the target node
must be an `Invoke` with a callback expecting the value.
Possible signatures:
`.select(key, value [, next ])`
`.select({ key: value } [, next])`
- `keyOrDict` Either a sequence to match, or a dictionary from sequences to values
- `valueOrNext` Either an integer value to be forwarded to the target node, or an otherwise node
- `next` Convenience param. Same as calling `.otherwise(...)`"""
if isinstance(keyOrDict, dict):
if not isinstance(valueOrNext, Node):
raise AssertionError("Invalid next argument of '.select()'")
if next:
raise AssertionError("Invalid argument count of '.select()'")
next = valueOrNext
for numKey, key in keyOrDict.items():
# print(f"{key}:{numKey}:{next}")
self.select(numKey, keyOrDict[numKey], next)
return self
# select(key,value,next)
assert isinstance(valueOrNext, int), (
"value Argument should be an integer not, %s" % (type(valueOrNext).__name__)
)
# raise AssertionError("Invalid `value` of argument .select()")
assert next is not None, "Invalid `next` of argument .select()"
value = int(valueOrNext)
key = toBuffer(keyOrDict)
edge = Edge(next, False, key, value)
# TODO: Put this on debug...
# if self.name == "nmethods":
# print(f"{self.name}: {key} -> {edge.node.name}")
self.addEdge(edge)
return self
def getTransform(self):
return self.transformFn
# TODO: (Vizonex) Rename _Span to MatchSpan?
class _Span(Match):
def __init__(self, name: str) -> None:
self.name = name
super().__init__(name)
class SpanStart(Node):
def __init__(self, span: "Span") -> None:
self.span = span
super().__init__(f"span_start_{span.callback.name}")
@property
def real_name(self):
"""Obtains span's original name"""
return self.span.callback.name
class SpanEnd(Node):
def __init__(self, span: "Span") -> None:
self.span = span
super().__init__(f"span_end_{span.callback.name}")
class Span:
def __init__(self, callback: _Span) -> None:
self.callback = callback
# NOTE Both SpanStart and SpanEnd have hash
# functions inherited from Node so no need to
# add anything special over there...
self.startCache: dict[Node, SpanStart] = {}
self.endCache: dict[Node, SpanEnd] = {}
# NOTE The thing that I'm greatful for seen in the orginal llparse typescript library
# is the ability to fork out and create all sorts of nodes whenever possible, these two
# functions personally demonstrate just that branching out concept alone - Vizonex
def start(self, otherwise: Node | None = None):
if otherwise and self.startCache.get(otherwise):
return self.startCache[otherwise]
res = SpanStart(self)
if otherwise:
res.otherwise(otherwise)
self.startCache[otherwise] = res
return res
def end(self, otherwise: Node | None = None):
if otherwise and self.endCache.get(otherwise):
return self.endCache[otherwise]
res = SpanEnd(self)
if otherwise:
res.otherwise(otherwise)
self.endCache[otherwise] = res
return res
class Reachability:
@staticmethod
def build(root: Node) -> list[Node]:
res: set[Node] = set()
queue = [root]
while queue:
node = queue.pop()
if node in res:
continue
res.add(node)
for edge in node:
queue.append(edge.node)
otherwise = node.getOtherwiseEdge()
if otherwise:
queue.append(otherwise.node)
return list(res)