-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJBobParser.py
More file actions
960 lines (604 loc) · 30.6 KB
/
Copy pathJBobParser.py
File metadata and controls
960 lines (604 loc) · 30.6 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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
### IMPORTS
import json
from math import nan, inf, isnan, isinf
from enum import Enum, auto
from typing import Any, Iterator, overload
from dataclasses import dataclass
### CONFIG
# If true, you can use single line comments in your json file,
# but be aware that this feature can raise errors when parsing
LINE_COMMENTS: bool = False
# Maximum capacity that json can hold
MAX_CAPACITY: int = 65355
# If true you can parse NaN values like NaN, Infinity (+Infinity) and -Infinity
# but if false only that you have is null value
PARSE_NAN_VALUES: bool = False
### HELPFUL
@overload
def _clamp(value: int, value_min: int, value_max: int) -> int: ...
@overload
def _clamp(value: float, value_min: float, value_max: float) -> float: ...
@overload
def _clamp[T](value: T, value_min: T, value_max: T) -> T: ...
def _clamp(value, value_min, value_max):
"""Clamps value between minimal and maximal values"""
return min(max(value, value_min), value_max)
def _convert_list_to_arr(values: list[Any]) -> ArrayNode:
"""Function that tries to convert Python's list to JsonArray (used for __setitem__)"""
result: list[JsonPrimaryNodes] = []
for value in values:
# If it's number
if isinstance(value, (int, float)):
if isnan(value) or isinf(value):
result.append(NaNNode(value))
else:
result.append(NumberNode(value))
# If it's string
elif isinstance(value, str):
result.append(StringNode(value))
# If it's boolean
elif isinstance(value, bool):
result.append(BooleanNode(value))
# If it's dictionary
elif isinstance(value, dict):
result.append(Parser(Scanner(json.dumps(value)).tokenize()).parse()[0])
# If it's another list
elif isinstance(value, list):
result.append(_convert_list_to_arr(value))
# If it's None
elif value is None:
result.append(NullNode())
# If it's unknown
else:
raise TypeError(f"Unexpected type of value '{type(value).__name__}'")
return ArrayNode(result)
### TOKENS
class TokenType(Enum):
"""Type of the token"""
Ident = auto()
NumberLit = auto()
StringLit = auto()
BoolLit = auto()
Comma = auto()
Colon = auto()
LBrace = auto()
RBrace = auto()
LBracket = auto()
RBracket = auto()
Minus = auto()
Plus = auto()
@dataclass
class Position:
"""Position of the token (line and column)"""
line: int
col: int
def __str__(self) -> str: return f"({self.line}, {self.col})"
__repr__ = __str__
@dataclass
class RangePos:
"""Ranged position of the token (start position and end position)"""
start_pos: Position
end_pos: Position
def __str__(self) -> str: return f"({self.start_pos} -> {self.end_pos})"
__repr__ = __str__
@dataclass
class Token:
"""Token class"""
type: TokenType
pos: RangePos
value: Any | None = None
def __str__(self) -> str: return f"Token({self.type}, {self.pos})" if self.value is None else f"Token({self.type}, {self.pos}, {repr(self.value)})"
__repr__ = __str__
### ERRORS
class ScannerError(Exception): ...
class ParserError(Exception): ...
class JsonError(Exception): ...
### Scanner
class Scanner:
def __init__(self, source: str) -> None:
"""Scanner constructor"""
self.source = iter(source) # Source text stream
self.source_lit = source # Source literal string (used for "peek")
self.index = -1 # Current index in source text stream
self.line = 1 # Current line in source text stream
self.col = 0 # Current column (character) in source text stream
self.advance() # First advance (getting first character)
self.cur_pos = Position(self.line, self.col) # Constructing "cur_pos" object
def advance(self) -> None:
"""Advances by 1 character"""
try:
self.cur_char = next(self.source)
self.index += 1
self.cur_pos = Position(self.line, self.col)
if self.cur_char == '\n':
self.line += 1
self.col = 1
else:
self.col += 1
except StopIteration:
self.cur_pos = Position(self.line, self.col)
if self.cur_char is not None:
self.col += 1
self.cur_char = None
def peek(self, offset: int = 0) -> str:
"""Peeks a character in source text stream with given offset"""
return self.source_lit[_clamp(self.index + offset, 0, len(self.source_lit) - 1)]
def eat(self) -> str:
"""Advances by 1 character and returns previous character"""
prev: str = self.peek()
self.advance()
return prev
def expect(self, char: str) -> None:
"""Expects the cur_char to be equal to the desired character\\
or to be in the string, and if so, than advances by 1 character\\
otherwise raises ScannerError (can raise TypeError)"""
if not isinstance(char, str):
raise TypeError("Expected 'str' type")
# single character
if len(char) == 1:
if self.cur_char != char:
raise ScannerError(f'Expected \'{char}\'')
self.advance()
# multiple characters
elif len(char) > 1:
if self.cur_char is not None and self.cur_char not in char:
raise ScannerError(f"Expected char as \"{char}\"")
self.advance()
def eat_expect(self, char: str) -> str:
"""Expects the cur_char to be equal to the desired character\\
or to be in the string, and if so, than advances by 1 character\\
and returns previous character"""
prev: str = self.peek()
self.expect(char)
return prev
def tokenize(self) -> list[Token]:
"""Tokenizes source text stream"""
tokens: list[Token] = []
while self.cur_char is not None:
# If we found comment we're raising exception
if not LINE_COMMENTS and self.cur_char == '/' and self.peek(offset = 1) == '/':
raise ScannerError(f"Unexpected comment at {self.cur_pos}")
# Feature with comments for JBobParser (i think it's useless)
elif LINE_COMMENTS and self.cur_char == '/' and self.peek(offset = 1) == '/':
while self.cur_char is not None and self.cur_char != '\n':
self.advance()
self.advance()
self.line += 1
self.col = 1
# Skipping spaces
elif self.cur_char.isspace():
while self.cur_char is not None and self.cur_char.isspace():
self.advance()
# Tokenizing numbers
elif self.cur_char.isdigit() or (self.cur_char == '.' and self.peek(offset = 1).isdigit()):
start_pos: Position = self.cur_pos
number: str = ''
points: int = 0
if self.cur_char == '.' and self.peek(1).isdigit():
points += 1
number += self.eat()
while self.cur_char is not None and (self.cur_char.isdigit() or self.cur_char == '.'):
if points > 1:
raise ScannerError(f'Invalid amount of points in float number at {self.cur_pos}')
number += self.eat()
if self.cur_char == '.':
points += 1
number += self.eat()
tokens.append(Token(TokenType.NumberLit, RangePos(start_pos, self.cur_pos), int(number) if points == 0 else float(number)))
# Tokenizing string
elif self.cur_char == '"':
start_pos: Position = self.cur_pos
self.advance() # Skipping "
string: str = ''
while self.cur_char is not None and self.cur_char != '"':
# If found escape character
while self.cur_char == '\\':
self.advance()
is_unicode: bool = False
match self.cur_char:
case '\\': string += '\\'
case '"': string += '\"'
case '\'': string += '\''
case 'n': string += '\n'
case 't': string += '\t'
case 'b': string += '\b'
case 'r': string += '\r'
case 'u':
is_unicode = True
symbol_addr: str = '0x'
digits: str = '0123456789abcdefABCDEF'
self.advance()
while self.cur_char != None and self.cur_char in digits:
symbol_addr += self.eat_expect(digits)
if len(symbol_addr) != 6 and self.peek() not in digits:
raise ScannerError(f"Unexpected character at {Position(self.line, self.col + 1)}")
if len(symbol_addr) > 6:
raise ScannerError(f'Expected exact 4 hexadecimal digits, but got {len(symbol_addr) - 2} at {self.cur_pos}')
string += chr(int(symbol_addr, 16))
case None: raise ScannerError(f"Expected escape character at {self.cur_pos}")
case _: raise ScannerError(f"Unexpected escape character '\\{self.cur_char}' at {self.cur_pos}")
# If it's not unicode we're skipping last character
# Why: "Hello, \\uffffTest"
# ^^^^^^^^ if we do not provide for this case, we will miss one extra character
if not is_unicode:
self.advance()
string += self.eat()
if self.cur_char is None or self.cur_char == '\n':
raise ScannerError(f"Expected \"")
self.advance() # Skipping "
tokens.append(Token(TokenType.StringLit, RangePos(start_pos, self.cur_pos), string))
# Tokenizing identifier/boolean
elif self.cur_char.isalnum():
start_pos: Position = self.cur_pos
ident: str = ''
while self.cur_char is not None and self.cur_char.isalnum():
ident += self.eat()
if ident in ('false', 'true'):
tokens.append(Token(TokenType.BoolLit, RangePos(start_pos, self.cur_pos), False if ident == 'false' else True))
elif ident in ("NaN", "Infinity", "null"):
tokens.append(Token(TokenType.Ident, RangePos(start_pos, self.cur_pos), nan if ident == "NaN" else inf if ident == "Infinity" else ident))
else:
raise ScannerError(f"Expected 'false' or 'true', but got '{ident}' at {start_pos}")
# Other symbols
else:
start_pos: Position = self.cur_pos
match self.cur_char:
case '+':
self.advance()
tokens.append(Token(TokenType.Plus, RangePos(start_pos, self.cur_pos), '+'))
case '-':
self.advance()
tokens.append(Token(TokenType.Minus, RangePos(start_pos, self.cur_pos), '-'))
case ':':
self.advance()
tokens.append(Token(TokenType.Colon, RangePos(start_pos, self.cur_pos), ':'))
case ',':
self.advance()
tokens.append(Token(TokenType.Comma, RangePos(start_pos, self.cur_pos), ','))
case '[':
self.advance()
tokens.append(Token(TokenType.LBracket, RangePos(start_pos, self.cur_pos), '['))
case ']':
self.advance()
tokens.append(Token(TokenType.RBracket, RangePos(start_pos, self.cur_pos), ']'))
case '{':
self.advance()
tokens.append(Token(TokenType.LBrace, RangePos(start_pos, self.cur_pos), '{'))
case '}':
self.advance()
tokens.append(Token(TokenType.RBrace, RangePos(start_pos, self.cur_pos), '}'))
case _:
print(start_pos)
raise ScannerError(f"Unexpected character '{self.cur_char}' at {self.cur_pos}")
return tokens
### NODES
class NodeBase:
"""Base of all nodes"""
type SetItemJsonBlockTypes = int | float | str | bool | None | list[SetItemJsonBlockTypes] | dict[str, SetItemJsonBlockTypes]
"""Used for __setitem__ function in JsonBlock"""
type JsonPrimaryTypes = int | float | str | bool | None | list[JsonPrimaryNodes] | JsonBlock
"""Supported types in JSON parsing"""
type JsonItems[K = str, V = JsonPrimaryTypes] = list[tuple[K, V]]
"""type like dict_items"""
type JsonPrimaryNodes = NumberNode | BooleanNode | StringNode | NaNNode | NullNode | ArrayNode | JsonBlock
"""Supported nodes in JSON parsing"""
# '{' (NODE ',')* '}'
@dataclass
class JsonBlock(NodeBase):
"""Main JSON block (or dictionary like)"""
nodes: list[Node]
def __find_key(self, key: str) -> int:
"""Function that tries to find a key in current JsonBlock"""
index: int = 0
for node in self.nodes:
if node.key.value == key:
return index
index += 1
raise JsonError(f'Unable to find key "{key}"')
def items(self) -> JsonItems[str, JsonPrimaryTypes]:
"""Returns JsonItems like dict_items"""
return [(
n.key.value,
n.value.value if not isinstance(n.value, JsonBlock) else\
n.value
) for n in self.nodes]
def keys(self) -> list[str]:
"""Returns keys of current JsonBlock"""
return [n.key.value for n in self.nodes]
def values(self) -> list[JsonPrimaryTypes]:
"""Returns values of current JsonBlock"""
return [n.value.value if not isinstance(n.value, JsonBlock) else n.value for n in self.nodes]
def __str__(self) -> str: return f"\x7B{', '.join(map(str, self.nodes))}\x7D"
__repr__ = __str__
def __iter__(self) -> Iterator[Node]:
return iter(self.nodes)
def __len__(self) -> int:
return len(self.nodes)
def __getitem__(self, key: str) -> JsonPrimaryNodes:
return self.nodes[self.__find_key(key)].value
def __setitem__(self, key: str, value: SetItemJsonBlockTypes) -> None:
key_index = self.__find_key(key)
if isinstance(value, (int, float)):
if isnan(value) or isinf(value):
self.nodes[key_index] = Node(StringNode(key), NaNNode(value))
else:
self.nodes[key_index] = Node(StringNode(key), NumberNode(value))
elif isinstance(value, str):
self.nodes[key_index] = Node(StringNode(key), StringNode(value))
elif isinstance(value, bool):
self.nodes[key_index] = Node(StringNode(key), BooleanNode(value))
elif isinstance(value, list):
self.nodes[key_index] = Node(StringNode(key), _convert_list_to_arr(value))
elif isinstance(value, dict):
self.nodes[key_index] = Node(StringNode(key), parse_string(json.dumps(value)))
elif value is None:
self.nodes[key_index] = Node(StringNode(key), NullNode())
else:
raise TypeError(f"Unexpected type of value '{type(value).__name__}'")
# STRING_LITERAL ':' JSON_PRIMARY_NODES
@dataclass
class Node(NodeBase):
"""JsonNode object (represents JSON field)"""
key: StringNode
value: JsonPrimaryNodes
def __str__(self) -> str: return f"{self.key}: {self.value}"
__repr__ = __str__
# "..."
@dataclass
class StringNode(NodeBase):
"""StringNode object (represents JSON string)"""
value: str
def __str__(self) -> str:
return f"\"{self.value.replace("\\", "\\\\")}\"" if '"' not in self.value else f"\"{self.value.replace("\\", "\\\\").replace('"', '\\"')}\""
__repr__ = __str__
# 1, 2.2, 3., .4
@dataclass
class NumberNode(NodeBase):
"""NumberNode object (represents JSON number)"""
value: int | float
def __str__(self) -> str: return f"{self.value}"
__repr__ = __str__
def __int__(self) -> int:
if isinstance(self.value, int):
return self.value
return int(self.value)
def __float__(self) -> float:
if isinstance(self.value, float):
return self.value
return float(self.value)
def __index__(self) -> int:
if not isinstance(self.value, int):
raise TypeError("Expected 'int' number")
return self.value
# false | true
@dataclass
class BooleanNode(NodeBase):
"""BooleanNode object (represents JSON boolean)"""
value: bool
def __str__(self) -> str: return 'false' if self.value else 'true'
__repr__ = __str__
def __bool__(self) -> bool:
return self.value
def __int__(self) -> int:
return int(self.value)
# NaN | -Infinity | Infinity
@dataclass
class NaNNode(NodeBase):
"""NaNNode object (represents JSON NaN, Infinity and -Infinity numbers)"""
value: float
def __float__(self):
return self.value
def __str__(self) -> str:
result: str = ""
if isnan(self.value):
result = "NaN"
elif self.value == -inf:
result = "-Infinity"
elif self.value == inf:
result = "Infinity"
return result
__repr__ = __str__
# null
@dataclass
class NullNode(NodeBase):
value: None = None
def __str__(self) -> str: return "null"
__repr__ = __str__
# [(LITERAL ',')*]
@dataclass
class ArrayNode(NodeBase):
"""ArrayNode object (represents JSON array)"""
value: list[JsonPrimaryNodes]
def __str__(self) -> str: return f"[{', '.join(map(repr, self.value))}]"
__repr__ = __str__
def __getitem__(self, index: int) -> JsonPrimaryNodes:
try:
return self.value[index]
except IndexError:
raise IndexError("Index out of range")
def __setitem__(self, key: int, value: JsonPrimaryTypes) -> None:
try:
if isinstance(value, (int, float)):
if isnan(value) or isinf(value):
self.value[key] = NaNNode(value)
else:
self.value[key] = NumberNode(value)
elif isinstance(value, str):
self.value[key] = StringNode(value)
elif isinstance(value, bool):
self.value[key] = BooleanNode(value)
elif isinstance(value, list):
self.value[key] = _convert_list_to_arr(value)
elif isinstance(value, dict):
self.value[key] = parse_string(json.dumps(value))
elif value is None:
self.value[key] = NullNode()
else:
raise TypeError(f"Unexpected type of value '{type(value).__name__}'")
except Exception as e:
raise e
### PARSER
class Parser:
def __init__(self, tokens: list[Token]) -> None:
"""Constructs JBobParser (Bobfob's JSON parser)"""
self.tokens = iter(tokens) # Tokens stream
self.tokens_lit = tokens # Literal tokens list (used for "peek")
self.index = -1 # Current index in token stream
self.fields_count = 0 # Fields count
self.advance() # First advance (getting first token)
def advance(self) -> None:
"""Advances through token stream"""
try:
# Getting next token and advancing index
self.cur_token = next(self.tokens)
self.index += 1
except StopIteration:
# Setting cur_token to None if we in the end of file
self.cur_token = None
def peek(self, offset: int = 0) -> Token:
"""Peeks token in token stream with given offset"""
return self.tokens_lit[_clamp(self.index + offset, 0, len(self.tokens_lit) - 1)]
def expect(self, token_type: TokenType, explanation: str = '', do_advance: bool = True) -> None:
"""Expects the type of cur_token to be equal to the desired token type\\
and if so, than advances by 1 token (or not) otherwise raises ParserError"""
if self.cur_token == None or self.cur_token.type != token_type:
raise ParserError(f"Expected '{explanation}', but got '{type(self.cur_token.value).__name__}' at {self.cur_token.pos}" if self.cur_token is not None else
f"Expected '{explanation}'")
if do_advance:
self.advance()
def eat_expect(self, token_type: TokenType, explanation: str = '', do_advance: bool = True) -> Token:
"""Expects the type of cur_token to be equal to the desired token type\\
and if so, than advances by 1 (or not) token and returns previous character\\
otherwise raises ParserError"""
prev = self.peek()
self.expect(token_type, explanation, do_advance)
return prev
def parse(self) -> tuple[JsonBlock, int]:
"""Parses JSON block"""
if self.cur_token == None:
raise ParserError("Expected token")
if self.cur_token.type == TokenType.LBrace:
self.advance()
fields = self.parse_fields()
self.expect(TokenType.RBrace, '}')
return JsonBlock(fields), self.fields_count
raise ParserError(f"Unexpected token '{self.cur_token.value}' at {self.cur_token.pos}")
def parse_fields(self) -> list[Node]:
"""Parses fields"""
fields: list[Node] = []
keys: list[str] = []
while self.cur_token is not None and self.cur_token.type != TokenType.RBrace:
# Parsing current field
field, pos = self.parse_field()
# Incrementing fields count
self.fields_count += 1
# Appending current key of the field (used for duplicated keys check)
keys.append(field.key.value)
# Raising ParserError if duplicated key was found
if len(keys) != len(set(keys)):
raise ParserError(f"Duplicated key found at {pos.start_pos}")
# Appending current field
fields.append(field)
# If fields count is greeter than MAX_CAPACITY we raising ParserError
if self.fields_count > MAX_CAPACITY:
raise ParserError("Fields count greeter then maximum capacity")
# Processing end of field
if self.cur_token is not None and self.cur_token.type != TokenType.RBrace:
self.expect(TokenType.Comma, ',')
# Checking for trailing comma
if self.cur_token.type == TokenType.RBrace:
raise ParserError(f"Unexpected trailing comma at {self.cur_token.pos}")
# Raising ParserError if we current at the end of file
elif self.cur_token is None:
raise ParserError("Expected '}'")
return fields
def parse_field(self) -> tuple[Node, RangePos]:
"""Parses current field"""
# Getting RangePos of current key
key_location: RangePos = self.eat_expect(TokenType.StringLit, 'str', do_advance = False).pos
# Getting current key
key: StringNode = self.parse_primary() # type: ignore
self.expect(TokenType.Colon, ':')
# Getting current value of the key
value: NodeBase = self.parse_primary()
# Returning tuple of current field (Node) and RangePos of current key
return Node(key, value), key_location
def parse_primary(self) -> JsonPrimaryNodes:
"""Parses primary"""
tok = self.cur_token
if tok is None:
raise ParserError(f"Expected token")
match tok.type:
# Found number literal
case TokenType.NumberLit:
self.advance()
return NumberNode(tok.value) # type: ignore
# Found string literal
case TokenType.StringLit:
self.advance()
return StringNode(tok.value) # type: ignore
# Found boolean literal
case TokenType.BoolLit:
self.advance()
return BooleanNode(tok.value) # type: ignore
# Found array
case TokenType.LBracket:
self.advance()
arr_values: list[JsonPrimaryNodes] = self.parse_arr_values()
self.expect(TokenType.RBracket, ']')
return ArrayNode(arr_values)
# Found NaN, Infinity or null
case TokenType.Ident:
self.advance()
if tok.value in (nan, inf):
return NaNNode(tok.value)
return NullNode()
# Found +Infinity
case TokenType.Plus:
self.advance()
value = self.eat_expect(TokenType.Ident, '+Infinity').value
return NaNNode(value) # type: ignore
# Found -Infinity
case TokenType.Minus:
self.advance()
value = self.eat_expect(TokenType.Ident, '-Infinity').value
return NaNNode(-value) # type: ignore
# Found another json
case TokenType.LBrace:
return self.parse()[0]
# Unknown token
case _:
raise ParserError(f"Unexpected token '{tok.value}' at {tok.pos}")
def parse_arr_values(self) -> list[JsonPrimaryNodes]:
"""Parses values in array"""
values: list[JsonPrimaryNodes] = []
while self.cur_token is not None and self.cur_token.type != TokenType.RBracket:
values.append(self.parse_primary())
# Processing end of value
if self.cur_token.type != TokenType.RBracket:
self.expect(TokenType.Comma, ',')
# Rasing ParserError if trailing comma was found
if self.cur_token.type == TokenType.RBracket:
raise ParserError(f"Unexpected trailing comma at {self.cur_token.pos}")
return values
def parse_string_with_count(source: str) -> tuple[JsonBlock, int]:
"""Parses source string and outputs parsed json and fields count"""
tokens: list[Token] = Scanner(source).tokenize()
tree, fields_count = Parser(tokens).parse()
return tree, fields_count
def parse_string(source: str) -> JsonBlock:
"""Parses source and outputs only parsed json without fields count"""
result, _ = parse_string_with_count(source)
return result
def parse_with_count(filename: str) -> tuple[JsonBlock, int]:
"""Parses source file and outputs parsed json and fields count"""
with open(filename, encoding="utf8") as f:
source = f.read()
return parse_string_with_count(source)
def parse(filename: str) -> JsonBlock:
"""Just parses source file and outputs only parsed json without fields count"""
result, _ = parse_with_count(filename)
return result
def dumps(tree: JsonBlock, *, indent: int = 4) -> str:
"""Converts parsed json into string"""
return json.dumps(json.loads(str(tree)), ensure_ascii=False, indent=indent)