-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpparser.py
1983 lines (1760 loc) · 78.7 KB
/
pparser.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
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MIT License
#
# Copyright (c) 2023 Roman Feduniak
#
# 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.
from contextlib import AbstractContextManager
from dataclasses import dataclass, field
from io import TextIOWrapper
import argparse
import typing
import enum
import sys
import re
import os
VERSION = "0.1.4"
RT = typing.TypeVar('RT') # return type
class TokenType(enum.Enum):
COMMENT = re.compile(r"#.*(?=\n)?")
IDENTIFIER = re.compile(r"[^\d\W]\w*")
EQUAL = re.compile(r"=")
SLASH = re.compile(r"/")
AMPERSAND = re.compile(r"&")
EXCLAMATION_MARK = re.compile(r"!")
STAR = re.compile(r"\*")
PLUS = re.compile(r"\+")
QUESTION_MARK = re.compile(r"\?")
LPAR = re.compile(r"\(")
RPAR = re.compile(r"\)")
LCBRACKET = re.compile(r"{")
RCBRACKET = re.compile(r"}")
PERCENT = re.compile(r"%")
COLON = re.compile(r":")
STRING = re.compile(r"\"[^\"\\]*(\\.[^\"\\]*)*\"")
CHARACTER_CLASS = re.compile(r"\[[^\]\\]*(\\.[^\]\\]*)*\]")
DOT = re.compile(r"\.")
TILDE = re.compile(r"~")
MINUS = re.compile(r"-")
# special tokens
CODE_SECTION = enum.auto()
ACTION = enum.auto()
RULE_TYPE = enum.auto()
def __repr__(self):
cls_name = self.__class__.__name__
return f'{cls_name}.{self.name}'
@dataclass
class Token:
type: TokenType
value: str
line: int
col: int
class Tokenizer:
def __init__(self, file: typing.TextIO):
self.filename = os.path.basename(file.name)
self.src = file.read()
self.tokens: list[Token] = []
self.pos = 0
def tokenize(self) -> list[Token]:
if self.tokens:
return self.tokens
while self.pos < len(self.src):
if self.src[self.pos].isspace():
self.pos += 1
# special token processing
elif len(self.tokens) >= 2 and \
self.tokens[-2].type == TokenType.PERCENT and self.tokens[-1].type == TokenType.IDENTIFIER and \
((name := self.tokens[-1].value) == "cpp" or name == "hpp"):
while self.src[self.pos].isspace():
self.pos += 1
if self.peek() == "{":
action_start, action_end = self.match_paired_characters("{", "}")
self.pos = action_end + 1
value = self.src[action_start + 1:action_end]
line_number = self.calc_line(action_start)
col = self.calc_column(action_start, line_number)
self.tokens.append(Token(TokenType.CODE_SECTION, value, line_number, col))
else:
self.error("'{' is expected")
elif self.peek() == "{":
action_start, action_end = self.match_paired_characters("{", "}")
self.pos = action_end + 1
value = self.src[action_start:action_end + 1]
line_number = self.calc_line(action_start)
col = self.calc_column(action_start, line_number)
self.tokens.append(Token(TokenType.ACTION, value, line_number, col))
elif self.peek() == "<":
type_start, type_end = self.match_paired_characters("<", ">")
self.pos = type_end + 1
value = self.src[type_start:type_end + 1]
line_number = self.calc_line(type_start)
col = self.calc_column(type_start, line_number)
self.tokens.append(Token(TokenType.RULE_TYPE, value, line_number, col))
else:
for token_type in TokenType:
# skip special tokens
if token_type in (TokenType.CODE_SECTION, TokenType.ACTION, TokenType.RULE_TYPE):
continue
if result := token_type.value.match(self.src, self.pos):
self.pos = result.end()
self.add_token(token_type, result.group())
break
else:
self.error(f"unknown character '{self.src[self.pos]}'")
return self.tokens
def match_paired_characters(self, open_char: str, close_char: str) -> tuple[int, int]:
mark = self.pos
open = 1
self.pos += 1
while self.pos < len(self.src):
if self.peek() == open_char:
open += 1
elif self.peek() == close_char:
open -= 1
if open == 0:
end_pos = self.pos
self.pos = mark
return mark, end_pos
self.pos += 1
self.error(f"'{close_char}' is expected")
def peek(self):
if self.pos >= len(self.src):
return None
return self.src[self.pos]
def calc_line(self, position: int) -> int:
return self.src.count("\n", 0, position) + 1
def calc_column(self, position: int, line: int) -> int:
lines = self.src.splitlines(keepends=True)
col = position if line == 1 else position - sum(map(len, lines[:line - 1]))
return col + 1
def add_token(self, token_type: TokenType, value: str = ""):
if token_type == TokenType.COMMENT:
return
position = self.pos - len(value)
line = self.calc_line(position)
col = self.calc_column(position, line)
self.tokens.append(Token(token_type, value, line, col))
def error(self, message) -> typing.NoReturn:
line_number = self.src.count("\n", 0, self.pos)
lines = self.src.splitlines(keepends=True)
col = self.pos + 1 if line_number == 0 else self.pos - sum(map(len, lines[:line_number])) + 1
print(f"{self.filename}:{line_number + 1}:{col}: {message}", file=sys.stderr)
sys.exit(1)
TNode = typing.TypeVar("TNode", bound="Node")
@dataclass(kw_only=True)
class Node():
line: int = 0
col: int = 0
def set_pos(self: TNode, start_token: Token) -> TNode:
self.line = start_token.line
self.col = start_token.col
return self
@dataclass
class BlockStatementNode(Node):
statements: list[Node]
@dataclass
class NameNode(Node):
name: str
@dataclass
class HeaderBlockNode(Node):
header: str
@dataclass
class CodeBlockNode(Node):
code: str
@dataclass
class RuleTypeNode(Node):
type_name: str
@dataclass
class RootRuleNode(Node):
name: str
@dataclass
class ParsingExpressionContext:
name: str | None = None
lookahead: bool = False
lookahead_positive: bool | None = None
loop: bool = False
loop_nonempty: bool | None = None
optional: bool = False
@dataclass(kw_only=True)
class ParsingExpressionNode(Node):
ctx: ParsingExpressionContext = field(default_factory=ParsingExpressionContext)
@dataclass
class ParsingExpressionRuleNameNode(ParsingExpressionNode):
name: str
@dataclass
class ParsingExpressionStringNode(ParsingExpressionNode):
value: str
@dataclass
class ParsingExpressionGroupNode(ParsingExpressionNode):
parsing_expression: list["ParsingExpressionSequence"]
@dataclass
class ParsingExpressionCharacterClassNode(ParsingExpressionNode):
characters: str
@dataclass
class ParsingExpressionDotNode(ParsingExpressionNode):
pass
@dataclass
class ParsingExpressionSequence(Node):
items: list[ParsingExpressionNode]
action: str | None = None
error_action: str | None = None
position_vars: set[str] = field(default_factory=set)
@dataclass
class RuleNode(Node):
name: str
expression_sequences: list[ParsingExpressionSequence]
return_type: str | None = None
is_left_recursive: bool = False
memo: bool = True
inline: bool = False
STRING_UNESCAPE_TABLE = {
"\\": "\\",
"\"": "\"",
"a": "\a",
"b": "\b",
"f": "\f",
"n": "\n",
"r": "\r",
"t": "\t",
"v": "\v",
}
CHARACTER_CLASS_UNESCAPE_TABLE = STRING_UNESCAPE_TABLE.copy()
CHARACTER_CLASS_UNESCAPE_TABLE.update({
"]": "]",
"[": "[",
})
def unescape_string(string: str, table: dict[str, str]) -> str:
new_string = ""
i = 0
while i < len(string) - 1:
ch = string[i]
next_ch = string[i + 1]
if ch == "\\" and next_ch in table:
new_string += table[next_ch]
i += 2
if i > len(string):
new_string += string[-1:]
else:
new_string += ch
i += 1
if i < len(string):
new_string += string[-1:]
return new_string
def escape_string(string: str) -> str:
escape_table = {
"\a": "a",
"\b": "b",
"\f": "f",
"\n": "n",
"\r": "r",
"\t": "t",
"\v": "v",
"\\": "\\",
"'": "\'",
}
new_string = ""
for ch in string:
if ch in escape_table:
new_string += "\\"
new_string += escape_table[ch]
else:
new_string += ch
return new_string
def string_to_bytes(string: str) -> bytes:
return re.sub(
rb"\\x[0-9a-fA-F]{2}",
lambda x: int(x.group(0)[-2:], 16).to_bytes(1, "big"),
string.encode()
)
class ParsingFail(Exception):
pass
class ParserManager(AbstractContextManager):
pos: int = 0
def __init__(self, parser: "Parser"):
self.parser = parser
def __enter__(self):
self.pos = self.parser.mark()
def __exit__(self, type, value, traceback) -> bool:
if type is not None:
if type == ParsingFail:
self.parser.reset(self.pos)
else:
raise
return True
class Parser:
def __init__(self, tokenizer: Tokenizer):
self.filename = tokenizer.filename
self.tokens = tokenizer.tokenize()
self.pos = 0
def parse(self) -> BlockStatementNode:
return self.root_block()
def root_block(self):
statements = []
while True:
try:
statements.append(self.statement())
except ParsingFail:
break
if self.pos != len(self.tokens):
self.error("parsing fail")
return BlockStatementNode(statements)
def statement(self):
with self.manager:
return self.name_statement()
with self.manager:
return self.header_statement()
with self.manager:
return self.code_statement()
with self.manager:
return self.rule_type_statement()
with self.manager:
return self.root_rule_statement()
with self.manager:
return self.rule_statement()
raise ParsingFail
def name_statement(self):
with self.manager:
self.match(TokenType.PERCENT)
if self.match(TokenType.IDENTIFIER).value == "name":
id = self.match(TokenType.IDENTIFIER)
return NameNode(id.value).set_pos(id)
raise ParsingFail
def header_statement(self):
with self.manager:
percent = self.match(TokenType.PERCENT)
if self.match(TokenType.IDENTIFIER).value == "hpp":
return HeaderBlockNode(self.match(TokenType.CODE_SECTION).value).set_pos(percent)
raise ParsingFail
def code_statement(self):
with self.manager:
self.match(TokenType.PERCENT)
if self.match(TokenType.IDENTIFIER).value == "cpp":
code = self.match(TokenType.CODE_SECTION)
return CodeBlockNode(code.value).set_pos(code)
raise ParsingFail
def rule_type_statement(self):
with self.manager:
self.match(TokenType.PERCENT)
if self.match(TokenType.IDENTIFIER).value == "type":
string = self.match(TokenType.STRING)
return RuleTypeNode(string.value[1:-1]).set_pos(string)
raise ParsingFail
def root_rule_statement(self):
with self.manager:
self.match(TokenType.PERCENT)
if self.match(TokenType.IDENTIFIER).value == "root":
id = self.match(TokenType.IDENTIFIER)
return RootRuleNode(id.value).set_pos(id)
raise ParsingFail
def parsing_expression_atom(self):
with self.manager:
id = self.match(TokenType.IDENTIFIER)
self.lookahead(False, TokenType.EQUAL)
self.lookahead(False, TokenType.RULE_TYPE)
self.lookahead(False, TokenType.MINUS)
return ParsingExpressionRuleNameNode(id.value).set_pos(id)
with self.manager:
str_token = self.match(TokenType.STRING)
string = unescape_string(str_token.value[1:-1], STRING_UNESCAPE_TABLE)
return ParsingExpressionStringNode(string).set_pos(str_token)
with self.manager:
lpar = self.match(TokenType.LPAR)
parsing_expressions = self.loop(True, self.parsing_expression_)
group = ParsingExpressionGroupNode([ParsingExpressionSequence(i).set_pos(lpar) for i in parsing_expressions]).set_pos(lpar)
self.match(TokenType.RPAR)
return group
with self.manager:
char_class = self.match(TokenType.CHARACTER_CLASS)
string = unescape_string(char_class.value[1:-1], CHARACTER_CLASS_UNESCAPE_TABLE)
return ParsingExpressionCharacterClassNode(string).set_pos(char_class)
with self.manager:
dot = self.match(TokenType.DOT)
return ParsingExpressionDotNode().set_pos(dot)
raise ParsingFail
def parsing_expression_item(self):
with self.manager:
atom = self.parsing_expression_atom()
self.match(TokenType.PLUS)
atom.ctx.loop = True
atom.ctx.loop_nonempty = True
return atom
with self.manager:
atom = self.parsing_expression_atom()
self.match(TokenType.STAR)
atom.ctx.loop = True
atom.ctx.loop_nonempty = False
return atom
with self.manager:
atom = self.parsing_expression_atom()
self.match(TokenType.QUESTION_MARK)
atom.ctx.optional = True
return atom
with self.manager:
return self.parsing_expression_atom()
with self.manager:
self.match(TokenType.AMPERSAND)
atom = self.parsing_expression_atom()
atom.ctx.lookahead = True
atom.ctx.lookahead_positive = True
return atom
with self.manager:
self.match(TokenType.EXCLAMATION_MARK)
atom = self.parsing_expression_atom()
atom.ctx.lookahead = True
atom.ctx.lookahead_positive = False
return atom
raise ParsingFail
def parsing_expression_named_item_or_item(self) -> ParsingExpressionNode:
with self.manager:
id = self.match(TokenType.IDENTIFIER)
self.match(TokenType.COLON)
item = self.parsing_expression_item()
item.ctx.name = id.value
return item
with self.manager:
return self.parsing_expression_item()
raise ParsingFail
def parsing_expression_(self):
with self.manager:
return self.loop(True, self.parsing_expression_named_item_or_item)
with self.manager:
self.match(TokenType.SLASH)
return self.loop(True, self.parsing_expression_named_item_or_item)
raise ParsingFail
def error_action(self):
with self.manager:
self.match(TokenType.TILDE)
return self.match(TokenType.ACTION)
return None
def parsing_expression(self):
with self.manager:
parsing_expression = self.parsing_expression_()
action = self.optional(TokenType.ACTION)
error_action = self.error_action()
node = ParsingExpressionSequence(
parsing_expression,
action.value if action else None,
error_action.value if error_action else None,
)
if action:
node.position_vars.update(re.findall(r"\$([1-9][0-9]*)", action.value))
node.line = parsing_expression[0].line
node.col = parsing_expression[0].col
return node
raise ParsingFail
def rule_attribute(self):
attr: Token
with self.manager:
self.match(TokenType.MINUS)
attr = self.match(TokenType.IDENTIFIER)
if attr.value in ("nomemo", "inline"):
return attr
self.error(f"Unknown rule attribute \"{attr.value}\"")
return None
def rule_statement(self):
with self.manager:
rule_name = self.match(TokenType.IDENTIFIER)
rule_type = self.optional(TokenType.RULE_TYPE)
attr = self.rule_attribute()
self.match(TokenType.EQUAL)
parsing_expressions = self.loop(True, self.parsing_expression)
rule_node = RuleNode(rule_name.value, parsing_expressions).set_pos(rule_name)
if rule_type:
rule_node.return_type = rule_type.value[1:-1].strip()
if attr:
match attr.value:
case "nomemo":
rule_node.memo = False
case "inline":
rule_node.inline = True
return rule_node
raise ParsingFail
@property
def manager(self):
return ParserManager(self)
def mark(self):
return self.pos
def reset(self, pos):
self.pos = pos
def get_token(self) -> Token | None:
if self.pos < len(self.tokens):
token = self.tokens[self.pos]
return token
return None
def match(self, token_type: TokenType) -> Token:
token = self.get_token()
if token and token.type == token_type:
self.pos += 1
return token
raise ParsingFail
def optional(self, token_type: TokenType) -> Token | None:
token = self.get_token()
if token and token.type == token_type:
self.pos += 1
return token
return None
def loop(self, nonempty, func: typing.Callable[..., RT], *args) -> list[RT]:
nodes = []
try:
while True:
node = func(*args)
nodes.append(node)
except ParsingFail:
pass
if len(nodes) >= nonempty:
return nodes
raise ParsingFail
def lookahead(self, positive: bool, token_type: TokenType):
if self.pos < len(self.tokens):
foo = self.tokens[self.pos].type == token_type
if foo == positive:
return
elif not positive:
return
raise ParsingFail
def error(self, message):
token = self.tokens[self.pos]
print(f"{self.filename}:{token.line}:{token.col}: {message}", file=sys.stderr)
sys.exit(1)
def write_lines(file: TextIOWrapper, *lines: str):
for line in lines:
file.write(line)
file.write("\n")
def add_indent(string: str, indent: int) -> str:
lines = string.split("\n")
new_lines = []
for line in lines:
new_lines.append((' ' * indent + line.rstrip()) if line.strip() else '')
return '\n'.join(new_lines)
def get_indent(string: str) -> int:
return len(string) - len(string.lstrip())
def remove_indent(string: str) -> str:
lines = string.split("\n")
new_lines = []
indent = min((get_indent(line) for line in lines if line.strip()))
for line in lines:
new_indent = get_indent(line) - indent
new_lines.append((' ' * new_indent + line.lstrip()) if line.strip() else '')
return '\n'.join(new_lines)
def set_indent(string: str, indent: int) -> str:
return add_indent(remove_indent(string), indent)
def get_return_type_of_parsing_expression_sequence(parsing_expression: ParsingExpressionSequence) -> "CppType":
if parsing_expression.action is None or "$$" not in parsing_expression.action:
return CppType("bool")
else:
return CppType("ExprResult", is_optional=True)
def count_by_predicate(container: typing.Iterable, predicate: typing.Callable[[typing.Any], bool]) -> int:
c = 0
for item in container:
if predicate(item):
c += 1
return c
def find_by_predicate(container: typing.Iterable, predicate: typing.Callable[[typing.Any], bool]):
for item in container:
if predicate(item):
return item
return None
@dataclass
class GeneratedExpression:
code: str
user_defined_var: str | None = None
@dataclass
class GeneratedGroupExpression:
code: str
user_defined_vars: list[str] = field(default_factory=list)
@dataclass
class CppType:
raw_type: str
is_optional: bool = False
def __str__(self) -> str:
if self.is_optional:
return f"std::optional<{self.raw_type}>"
return self.raw_type
def is_bool(self) -> bool:
return self.raw_type == "bool"
@property
def null(self) -> str:
if self.is_optional:
return "std::nullopt"
if self.raw_type == "bool":
return "false"
assert False, f"not implemented for type '{self.raw_type}'"
@property
def getter(self) -> str:
if self.is_optional:
return ".value()"
return ""
class AstContext:
def __init__(self, root_node: BlockStatementNode, filename: str):
self.root_node = root_node
self.filename = filename
if r := self.get_node_or_none(RootRuleNode):
self.root_rule: RuleNode = self.get_rule_by_name(r.name) # type: ignore
else:
self.root_rule: RuleNode = self.get_node_or_none(RuleNode) # type: ignore
def get_rule_by_name(self, name: str) -> RuleNode | None:
return find_by_predicate(
self.root_node.statements, lambda node: isinstance(node, RuleNode) and node.name == name)
def get_node_or_none(self, node_type: typing.Type[RT]) -> RT | None:
for item in self.root_node.statements:
if isinstance(item, node_type):
return item
def get_rules(self) -> list[RuleNode]:
rules = []
for statement in self.root_node.statements:
if isinstance(rule := statement, RuleNode):
rules.append(rule)
return rules
def get_rule_names(self) -> list[str]:
return [rule.name for rule in self.get_rules()]
def get_node_count(self, node_type: typing.Type[Node]) -> int:
return count_by_predicate(self.root_node.statements, lambda node: isinstance(node, node_type))
class LeftRecursiveAnalyzer:
def __init__(self, ctx: AstContext):
self.ctx = ctx
def analyze(self):
for rule in self.ctx.get_rules():
if not rule.inline:
rule.is_left_recursive = self.is_direct_left_recursive(rule)
def is_direct_left_recursive(self, rule: RuleNode) -> bool:
for sequence in rule.expression_sequences:
if first_rule := self.get_first_rule_or_none(sequence):
if first_rule.name == rule.name:
return True
return False
def get_first_rule_or_none(self, sequence: ParsingExpressionSequence) -> ParsingExpressionRuleNameNode | None:
for item in sequence.items:
if isinstance(item, ParsingExpressionRuleNameNode):
return item
elif isinstance(item, ParsingExpressionGroupNode):
return self.get_first_rule_or_none(item.parsing_expression[0])
elif not self.is_parsing_expr_consume_zero(item):
break
return None
def is_parsing_expr_consume_zero(self, expr: ParsingExpressionNode) -> bool:
if expr.ctx.optional \
or expr.ctx.lookahead \
or expr.ctx.loop and not expr.ctx.loop_nonempty \
or isinstance(expr, ParsingExpressionRuleNameNode) and self.is_rule_consume_zero(expr.name):
return True
return False
def is_rule_consume_zero(self, rule_name: str) -> bool:
rule: RuleNode = self.ctx.get_rule_by_name(rule_name) # type: ignore
for sequence in rule.expression_sequences:
zero_consume = True
for item in sequence.items:
if not self.is_parsing_expr_consume_zero(item):
zero_consume = False
break
if zero_consume:
return True
return False
class StaticAnalyzer:
def __init__(self, ctx: AstContext):
self.ctx = ctx
def analyze(self):
self.rules_presence()
self.same_rule_names()
self.check_directives()
self.check_rule_name_in_root_directive()
self.rule_not_exist_but_used()
self.unused_rules()
LeftRecursiveAnalyzer(self.ctx).analyze() # only after check unused rules
self.wrong_left_recursive_rules()
self.check_action_presence() # check for the presence of an action when variables are present
self.same_var_names_in_parsing_expr_sequence()
self.group_with_repetition_has_variables_inside()
self.lookahead_false_assigned_to_var()
self.string_assigned_to_var()
# The return types in all parsing expression sequences must match within the rule
self.check_return_types_in_parsing_expression_sequences()
self.check_characters_inside_character_class()
self.check_position_vars_in_action()
self.check_nomemo_attr()
self.check_inline_attr()
def rules_presence(self):
if self.ctx.get_node_or_none(RuleNode) is None:
self.error("No rule is defined")
def same_rule_names(self):
rule_names = self.ctx.get_rule_names()
for i, rule_name in enumerate(rule_names[:-1], 1):
for rule_name_ in rule_names[i:]:
if rule_name == rule_name_:
self.error(f"Rule '{rule_name}' has more than one definition")
def check_directives(self):
error_message = "The '%{}' directive has more than one definition"
if self.ctx.get_node_count(NameNode) > 1:
self.error(error_message.format("name"))
if self.ctx.get_node_count(HeaderBlockNode) > 1:
self.error(error_message.format("hpp"))
if self.ctx.get_node_count(CodeBlockNode) > 1:
self.error(error_message.format("cpp"))
if self.ctx.get_node_count(RuleTypeNode) > 1:
self.error(error_message.format("type"))
if self.ctx.get_node_count(RootRuleNode) > 1:
self.error(error_message.format("root"))
def check_rule_name_in_root_directive(self):
if root_rule_node := self.ctx.get_node_or_none(RootRuleNode):
if root_rule_node.name not in self.ctx.get_rule_names():
self.error(f"The directive '%root' contains a non-existing rule: '{root_rule_node.name}'", root_rule_node)
def rule_not_exist_but_used(self):
rule_names = self.ctx.get_rule_names()
for rule in self.ctx.get_rules():
for sequence in rule.expression_sequences:
for item in sequence.items:
if isinstance(item, ParsingExpressionRuleNameNode):
if item.name not in rule_names:
self.error(f"The '{rule.name}' rule invokes a nonexistent rule '{item.name}'", item)
def unused_rules(self):
checked_rules = []
def group_traversal(group: ParsingExpressionGroupNode) -> set[str]:
rules = set()
for sequence in group.parsing_expression:
for item in sequence.items:
if isinstance(r := item, ParsingExpressionRuleNameNode):
if r.name not in checked_rules:
rules.add(r.name)
rules.update(rule_traversal(self.ctx.get_rule_by_name(r.name))) # type: ignore
elif isinstance(g := item, ParsingExpressionGroupNode):
rules.update(group_traversal(g))
return rules
def rule_traversal(rule: RuleNode) -> set[str]:
checked_rules.append(rule.name)
rules = set()
for sequence in rule.expression_sequences:
for item in sequence.items:
if isinstance(r := item, ParsingExpressionRuleNameNode):
if r.name not in checked_rules:
rules.add(r.name)
rules.update(rule_traversal(self.ctx.get_rule_by_name(r.name))) # type: ignore
elif isinstance(g := item, ParsingExpressionGroupNode):
rules.update(group_traversal(g))
return rules
used_rules = rule_traversal(self.ctx.root_rule)
used_rules.add(self.ctx.root_rule.name)
all_rules = set(self.ctx.get_rule_names())
if len(unused_rules := all_rules - used_rules):
error_messages = []
for unused_rule_name in unused_rules:
unused_rule_node: RuleNode = self.ctx.get_rule_by_name(unused_rule_name) # type: ignore
error_messages.append(f"{self.ctx.filename}:{unused_rule_node.line}:{unused_rule_node.col}:"
f" Rule '{unused_rule_name}' defined but not used")
self.error("\n".join(error_messages))
def wrong_left_recursive_rules(self):
for rule in self.ctx.get_rules():
if rule.is_left_recursive:
if len(rule.expression_sequences) == 1:
self.error(f"In the '{rule.name}' name, a left-recursive rule must be at least 2 sequences of expressions", rule)
def check_action_presence(self):
for rule in self.ctx.get_rules():
is_rule_type_specified = bool(rule.return_type)
for parsing_expression_sequence in rule.expression_sequences:
is_var_presence = False
for item in parsing_expression_sequence.items:
if isinstance(group := item, ParsingExpressionGroupNode):
if len(self.get_vars_from_group(group)):
is_var_presence = True
break
if item.ctx.name:
is_var_presence = True
break
if is_var_presence and parsing_expression_sequence.action is None:
self.error(f"In the '{rule.name}' rule, variables are declared, but there is no action", parsing_expression_sequence)
if is_rule_type_specified:
if parsing_expression_sequence.action is None:
self.error(f"In the '{rule.name}' rule, the return type is defined, but the action not specified",
parsing_expression_sequence)
elif "$$" not in parsing_expression_sequence.action:
self.error(f"In the '{rule.name}' rule, the return type is defined, but '$$' variable in the action is not",
parsing_expression_sequence)
def same_var_names_in_parsing_expr_sequence(self):
error_message = "In the '{}' rule, variable '{}' is declared multiple times"
for rule in self.ctx.get_rules():
for parsing_expression_sequence in rule.expression_sequences:
var_names = []
for item in parsing_expression_sequence.items:
if isinstance(group := item, ParsingExpressionGroupNode):
for var in self.get_vars_from_group(group):
if var in var_names:
self.error(error_message.format(rule.name, var), parsing_expression_sequence)
var_names.append(var)
if (var := item.ctx.name):
if var in var_names:
self.error(error_message.format(rule.name, var), parsing_expression_sequence)
var_names.append(var)
def group_with_repetition_has_variables_inside(self):
for rule in self.ctx.get_rules():
for parsing_expression_sequence in rule.expression_sequences:
for item in parsing_expression_sequence.items:
if isinstance(group := item, ParsingExpressionGroupNode):
if group.ctx.loop and len(self.get_vars_from_group(group)):
self.error(f"In the '{rule.name}' rule, the group uses variables inside itself"
" and repetitions operators simultaneously", group)
def lookahead_false_assigned_to_var(self):
for rule in self.ctx.get_rules():
for parsing_expression_sequence in rule.expression_sequences:
for item in parsing_expression_sequence.items:
if item.ctx.lookahead and not item.ctx.lookahead_positive and item.ctx.name:
self.error(f"In the '{rule.name}' rule, a parsing expression with the '!' operator"
" cannot be assigned to a variable", item)
def string_assigned_to_var(self):
for rule in self.ctx.get_rules():
for parsing_expression_sequence in rule.expression_sequences:
for item in parsing_expression_sequence.items:
if isinstance(string := item, ParsingExpressionStringNode):
if string.ctx.name:
if string.ctx.lookahead:
self.error(f"In the '{rule.name}' rule, a string with the '&' operator"
" cannot be assigned to a variable", string)
if not string.ctx.loop and not string.ctx.optional:
self.error(f"In the '{rule.name}' rule, simple string cannot be assigned to a variable", string)
def check_return_types_in_parsing_expression_sequences(self):
for rule in self.ctx.get_rules():
if len(rule.expression_sequences) > 1:
return_type = get_return_type_of_parsing_expression_sequence(rule.expression_sequences[0])
for parsing_expression_sequence in rule.expression_sequences[1:]:
if return_type != get_return_type_of_parsing_expression_sequence(parsing_expression_sequence):
self.error(f"In the '{rule.name}' rule, parsing expression sequences return different types", rule)
def check_characters_inside_character_class(self):
for rule in self.ctx.get_rules():
for parsing_expression_sequence in rule.expression_sequences:
for item in parsing_expression_sequence.items:
if isinstance(character_class := item, ParsingExpressionCharacterClassNode):
characters = []