-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokens_and_grammar.py
1237 lines (948 loc) Β· 28.9 KB
/
tokens_and_grammar.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
from ply.lex import lex
from ply.yacc import yacc
from utils.errors import PintException
from utils.utils import *
# --- Tokenizer ---
# All tokens must be named in advance.
tokens = (
"TYPE", "INT", "FLOAT", "BOOLEAN", "STRING", "NONE",
"IDENTIFIER", "CLASS", "INHERITS",
"LBRACE", "RBRACE", "LPAREN", "RPAREN", "LBRACKET", "RBRACKET", "LEFTARROW", "RIGHTARROW",
"COLON", "COMMA", "DOT",
"ASSIGN", "PLUSASSIGN", "MINUSASSIGN", "TIMESASSIGN", "DIVIDEASSIGN", "MODULOASSIGN", "POWERASSIGN", "FLOORASSIGN",
"PLUS", "MINUS", "TIMES", "DIVIDE", "MODULO", "POWER", "FLOOR",
"LESS", "LESSEQUAL", "GREATER", "GREATEREQUAL", "EQUAL", "NOTEQUAL",
"AND", "OR", "NOT",
"ONELINECOMMENT", "MULTILINECOMMENT",
"LIST", "TUPLE", "DICT", "SET",
"FUNCTION", "RETURNARROW", "CONSTRUCTOR",
"TREE", "LEAF", "FALLENLEAF",
"LOOP",
"BREAK", "CONTINUE", "RETURN", "PASS",
"NEWLINE",
"SELF",
"IMPORT", "FROM", "AS",
"PRINT",
)
# Ignored characters - spaces and tabs
t_ignore = " \t"
# Token matching rules are written as regexs
t_TYPE = r"π’|βΊοΈ|π|π "
t_LEFTARROW = r"<"
t_RIGHTARROW = r">"
t_BOOLEAN = r"β
|β"
t_STRING = r"\".*\"|βοΈ\β.*\β"
t_NONE = r"π"
t_IDENTIFIER = r"[a-zA-Z_][a-zA-Z0-9_]*"
t_CLASS = r"ποΈ"
t_INHERITS = r"π¨βπ¦"
t_SELF = r"π€"
t_CONSTRUCTOR = r"ποΈ"
t_FUNCTION = r"πΊ"
t_RETURNARROW = r"->"
t_LBRACE = r"\{"
t_RBRACE = r"\}"
t_LPAREN = r"\("
t_RPAREN = r"\)"
t_LBRACKET = r"\["
t_RBRACKET = r"\]"
t_COLON = r":"
t_COMMA = r","
t_DOT = r"\."
# assignment operators
t_ASSIGN = r"="
t_PLUSASSIGN = r"\+="
t_MINUSASSIGN = r"-="
t_TIMESASSIGN = r"\*="
t_DIVIDEASSIGN = r"/="
t_MODULOASSIGN = r"%="
t_POWERASSIGN = r"\^="
t_FLOORASSIGN = r"//="
# arithmetic operators
t_PLUS = r"\+"
t_MINUS = r"-"
t_TIMES = r"\*"
t_DIVIDE = r"/"
t_MODULO = r"%"
t_POWER = r"\^"
t_FLOOR = r"//"
# comparison operators
t_LESS = r"π"
t_LESSEQUAL = r"πβοΈ"
t_GREATER = r"π"
t_GREATEREQUAL = r"πβοΈ"
t_EQUAL = r"βοΈ"
# logical operators
# t_AND = r"and"
# t_OR = r"or"
# t_NOT = r"not"
t_AND = r'π'
t_OR = r'π'
t_NOT = r'π‘'
# data structures
t_LIST = r"π"
t_TUPLE = r"πΌ"
t_DICT = r"πΊοΈ"
t_SET = r"ποΈ"
# if and match
t_TREE = r"π²"
t_LEAF = r"π"
t_FALLENLEAF = r"π"
# loops
t_LOOP = r"π"
# flow control
t_BREAK = r"π"
t_CONTINUE = r"π¦"
t_RETURN = r"π¦"
t_PASS = r"π¦₯"
# importing
t_IMPORT = r"π’"
t_FROM = r"ποΈ"
t_AS = r"π€Ώ"
# aliases
t_PRINT = r"π¨οΈ"
# A function can be used if there is an associated action.
# Write the matching regex in the docstring.
def t_FLOAT(t):
r"(\+|-)?\d+\.\d+"
t.value = float(t.value)
return t
def t_INT(t):
r"(\+|-)?\d+"
t.value = int(t.value)
return t
# t_NEWLINE = r'\n'
def t_NEWLINE(t):
r"\n"
t.lexer.lineno += 1
return t
# t_COMMENT = r'(π¬β¬οΈ(.|\n)*?π¬β¬οΈ\n)|(π¬.*\n)'
def t_MULTILINECOMMENT(t):
r"π¬β¬οΈ(.|\n)*?π¬β¬οΈ\n"
t.lexer.lineno += t.value.count("\n")
return t
def t_ONELINECOMMENT(t):
r"π¬.*\n"
t.lexer.lineno += 1
return t
# Error handler for illegal characters
def t_error(t):
last_cr = t.lexer.lexdata.rfind("\n", 0, t.lexpos)
if last_cr < 0:
last_cr = 0
column = (t.lexpos - last_cr)
raise PintException("Illegal character", "", t.lexer.lineno, column, t.value[0])
# Build the lexer object
lexer = lex()
# --- Parser ---
spacing = 4 * " "
variables = {}
types = {
"π’": "int",
"βΊοΈ": "float",
"π": "bool",
"π ": "str",
"π": "list",
"πΌ": "tuple",
"πΊοΈ": "dict",
"ποΈ": "set",
}
emoji_operators = {"π": "<", "πβοΈ": "<=", "π": ">", "πβοΈ": ">=", "βοΈ": "=="}
current_scope = Scope("global", None)
def indent(lines):
lines = lines.strip().split("\n")
lines = [spacing + line for line in lines]
lines = "\n".join(lines)
return lines
def get_type(type_):
if len(type_) == 1:
return types[type_]
else:
args = [get_type(t) for t in type_[1:] if t not in ("<", ">", " ", ",")]
return f'{types[type_[0]]}[{", ".join(args)}]'
# PROGRAM
start = "program"
def p_program(p):
"""
program : nonexecutables imports nonexecutables definitions_and_statements nonexecutables
"""
p[0] = "".join(p[1:])
# NEWLINES
def p_newlines(p):
"""
newlines : newlines NEWLINE
| NEWLINE
"""
p[0] = "".join(p[1:])
# EMPTY
def p_empty(p):
"""
empty :
"""
p[0] = ""
# IMPORTS
def p_imports(p):
"""
imports : imports nonexecutables import
| import
| empty
"""
p[0] = "".join(p[1:])
def p_import(p):
"""
import : IMPORT compound_identifier NEWLINE
| IMPORT compound_identifier AS IDENTIFIER NEWLINE
| IMPORT compound_identifier FROM compound_identifier NEWLINE
| IMPORT compound_identifier FROM compound_identifier AS IDENTIFIER NEWLINE
"""
match p[1:]:
case ["π’", _, "\n"]:
p[0] = f"import {p[2]}\n"
case ["π’", _, "π€Ώ", _, "\n"]:
p[0] = f"import {p[2]} as {p[4]}\n"
case ["π’", _, "ποΈ", _, "\n"]:
p[0] = f"from {p[4]} import {p[2]}\n"
case ["π’", _, "ποΈ", _, "π€Ώ", _, "\n"]:
p[0] = f"from {p[4]} import {p[2]} as {p[6]}\n"
case _:
p[0] = "\n"
# DEFINITIONS AND STATEMENTS
def p_definitions_and_statements(p):
"""
definitions_and_statements : definitions_and_statements nonexecutables definition
| definitions_and_statements nonexecutables statement
| definition
| statement
| empty
"""
p[0] = "".join(p[1:])
# TYPES
def p_type(p):
"""
type : TYPE
| IDENTIFIER
| LIST LEFTARROW type RIGHTARROW
| TUPLE LEFTARROW types RIGHTARROW
| DICT LEFTARROW type COMMA type RIGHTARROW
| SET LEFTARROW type RIGHTARROW
"""
p[0] = (types[p[1]] + "".join(p[2:])).replace("<", "[").replace(">", "]")
def p_types(p):
"""
types : types COMMA type
| type
"""
# p[0] = p[1] if len(p) == 2 else ", ".join(p[1:])
# p[0] = p[1] if len(p) == 2 else " ".join(p[1:])
p[0] = str(p[1]) + ", " + str(p[3]) if len(p) > 2 else str(p[1])
# DEFINITION
def p_definition(p):
"""
definition : class_definition
| function_definition
| variable_definition
"""
p[0] = p[1]
# VARIABLE DEFINITION
def p_variable_definition(p):
"""
variable_definition : type IDENTIFIER ASSIGN expression NEWLINE
| type IDENTIFIER ASSIGN expression oneline_comment
"""
global current_scope
if current_scope.contains_variable(p[2]):
raise PintException("Definition error", f"Variable \"{p[2]}\" already defined in scope {current_scope.name}", p.lexer.lineno - 1, 1, None)
else:
current_scope.variables[p[2]] = Variable(p[2], p[1], p[4])
match p[-1]:
case "\n":
p[0] = f"{p[2]}: {p[1]} = {str(p[4])}\n"
case _:
p[0] = f"{p[2]}: {p[1]} = {str(p[4])} {p[5]}"
# FUNCTION DEFINITION
def p_function_definition(p):
"""
function_definition : function_naming LPAREN parameters RPAREN RETURNARROW type LBRACE NEWLINE function_body RBRACE NEWLINE
| function_naming LPAREN parameters RPAREN RETURNARROW NONE LBRACE NEWLINE function_body RBRACE NEWLINE
"""
global current_scope
current_scope = current_scope.parent
current_scope.functions[p[1].name].parameters = p[3]
current_scope.functions[p[1].name].return_type = p[6]
current_scope.functions[p[1].name].body = p[9]
p[0] = f"def {p[1].name}({p[3]}) -> {p[6].replace('π', 'None')}:\n{indent(p[9])}\n"
def p_function_naming(p):
"""
function_naming : FUNCTION IDENTIFIER
"""
global current_scope
if current_scope.contains_function(p[2]):
raise PintException("Definition error", f"Function \"{p[2]}\" already defined in scope {current_scope.name}", p.lexer.lineno, 1, None)
else:
current_scope.functions[p[2]] = p[0] = Function(p[2], None, None, None)
current_scope = FunctionScope(p[2], current_scope)
def p_function_body(p):
"""
function_body : function_body statement nonexecutables
| function_body variable_definition nonexecutables
| function_body function_definition nonexecutables
| nonexecutables
| empty
"""
p[0] = "".join(p[1:])
# STATEMENTS
# @TODO: Add support for try and raise statements
def p_statement(p):
"""
statement : assignment_statement
| call_statement
| if_statement
| match_statement
| loop_statement
| continue_statement
| break_statement
| return_statement
| pass_statement
| NEWLINE
"""
p[0] = p[1]
def p_statements(p):
"""
statements : statements comments statement
| statement
| empty
"""
p[0] = "".join(p[1:])
def p_return_statement(p):
"""
return_statement : RETURN expression NEWLINE
| RETURN NEWLINE
"""
p[0] = "return " + p[2] + "\n" if len(p) > 3 else "return\n"
# ASSIGNMENT
def p_assignment_statement(p):
"""
assignment_statement : compound_identifier assign expression NEWLINE
| subscript_expression assign expression NEWLINE
| compound_identifier assign expression oneline_comment
| subscript_expression assign expression oneline_comment
"""
global current_scope
variable_basename = (
p[1].split(".")[0] if "." in p[1] and not "self" in p[1]
else p[1].split(".")[1] if "." in p[1]
else p[1].split("[")[0] if "[" in p[1]
else p[1]
)
if not current_scope.contains_variable(variable_basename):
raise PintException(
"Assignment error",
f"Variable \"{variable_basename}\" not defined in scope {current_scope.name}",
p.lexer.lineno - 2,
1,
None
)
# @TODO: compound identifiers in scope? value update? is keeping track of variable value necessary?
match p[-1]:
case "\n":
p[0] = f"{p[1]} {p[2]} {p[3]}\n"
case _:
p[0] = f"{p[1]} {p[2]} {p[3]} {p[4]}"
def p_assign(p):
"""
assign : ASSIGN
| PLUSASSIGN
| MINUSASSIGN
| TIMESASSIGN
| DIVIDEASSIGN
| MODULOASSIGN
| POWERASSIGN
| FLOORASSIGN
"""
if p[1] == "^=":
p[0] = "**="
else:
p[0] = p[1]
# CALL
def p_call_statement(p):
"""
call_statement : call NEWLINE
"""
p[0] = p[1] + "\n"
# IF
def p_if_statement(p):
"""
if_statement : simple_if_statement
| compound_if_statement
"""
p[0] = p[1]
def p_simple_if_statement(p):
"""
simple_if_statement : LEAF LPAREN expression RPAREN LBRACE NEWLINE if_body RBRACE NEWLINE
"""
if p[7].isspace() or not p[7]:
p[7] = "pass"
p[0] = f"if {p[3]}:\n{indent(p[7])}\n"
def p_if_body(p):
"""
if_body : if_body statement nonexecutables
| if_body variable_definition nonexecutables
| nonexecutables
| empty
"""
p[0] = "".join(p[1:])
def p_compound_if_statement(p):
"""
compound_if_statement : TREE LBRACE NEWLINE if_elseif_statements else_block RBRACE NEWLINE
| TREE LBRACE NEWLINE if_elseif_statements RBRACE NEWLINE
"""
p[0] = p[4] + p[5] if len(p) > 7 else p[4]
def p_if_elseif_statements(p):
"""
if_elseif_statements : if_elseif_statements elseif_statement
| simple_if_statement
"""
p[0] = "".join(p[1:])
def p_elseif_statement(p):
"""
elseif_statement : LEAF LPAREN expression RPAREN LBRACE NEWLINE if_body RBRACE NEWLINE
"""
if p[7].isspace() or not p[7]:
p[7] = "pass"
p[0] = f"elif {p[3]}:\n{indent(p[7])}\n"
def p_else_block(p):
"""
else_block : FALLENLEAF LBRACE NEWLINE if_body RBRACE NEWLINE
"""
if p[4].isspace() or not p[4]:
p[4] = "pass"
p[0] = f"else:\n{indent(p[4])}\n"
# MATCH
def p_match_statement(p):
"""
match_statement : TREE LPAREN compound_identifier RPAREN LBRACE NEWLINE match_cases match_default RBRACE NEWLINE
"""
p[0] = f"match {p[3]}:\n{indent(p[7])}\n{indent(p[8])}\n"
def p_match_cases(p):
"""
match_cases : match_cases match_case
| match_case
"""
p[0] = "".join(p[1:])
def p_match_case(p):
"""
match_case : LEAF LPAREN expression RPAREN LBRACE case_body RBRACE NEWLINE
"""
if p[6].isspace() or not p[6]:
p[6] = "pass"
p[0] = f"case {p[3]}:\n{indent(p[6])}\n"
def p_match_default(p):
"""
match_default : FALLENLEAF LBRACE case_body RBRACE NEWLINE
"""
if p[3].isspace() or not p[3]:
p[3] = "pass"
p[0] = f"case _:\n{indent(p[3])}\n"
def p_case_body(p):
"""
case_body : case_body statement nonexecutables
| case_body variable_definition nonexecutables
| nonexecutables
| empty
"""
p[0] = "".join(p[1:])
# LOOP
def p_loop_statement(p):
"""
loop_statement : while_statement
| for_statement
"""
p[0] = p[1]
# WHILE, INFINITE LOOP
def p_while_statement(p):
"""
while_statement : loop_beginning LPAREN expression RPAREN LBRACE NEWLINE statements RBRACE NEWLINE
| loop_beginning LBRACE NEWLINE statements RBRACE NEWLINE
"""
global current_scope
statements = p[7] if len(p) == 10 else p[4]
if statements.isspace() or not statements:
statements = "pass"
statements = indent(statements)
condition = p[3] if len(p) == 10 else "True"
current_scope = current_scope.parent
p[0] = f"while {condition}:\n{statements}\n"
def p_loop_beginning(p):
"""
loop_beginning : LOOP
"""
global current_scope
current_scope = Scope("loop", current_scope)
p[0] = p[1]
# FOR
def p_for_statement(p):
"""
for_statement : for_beginning LBRACE NEWLINE definitions_and_statements RBRACE NEWLINE
"""
global current_scope
current_scope = current_scope.parent
if p[4].isspace() or not p[4]:
p[4] = "pass"
p[0] = f"{p[1]}\n{indent(p[4])}\n"
def p_for_beginning(p):
"""
for_beginning : loop_beginning LPAREN type IDENTIFIER ASSIGN expression RPAREN
"""
global current_scope
current_scope.variables[p[4]] = Variable(p[4], p[3])
p[0] = f"for {p[4]} in {p[6]}:"
# CONTINUE, BREAK, PASS
def p_continue_statement(p):
"""
continue_statement : CONTINUE NEWLINE
"""
p[0] = "continue\n"
def p_break_statement(p):
"""
break_statement : BREAK NEWLINE
"""
p[0] = "break\n"
def p_pass_statement(p):
"""
pass_statement : PASS NEWLINE
"""
p[0] = "pass\n"
# COMMENTS
def p_comment(p):
"""
comment : oneline_comment
| multiline_comment
"""
p[0] = p[1]
def p_multiline_comment(p):
"""
multiline_comment : MULTILINECOMMENT
"""
lines = p[1].replace("π¬β¬οΈ", "").replace("π¬β¬οΈ", "").strip().split("\n")
lines = ["# " + line.strip() for line in lines]
lines = "\n".join(lines) + "\n"
p[0] = lines
def p_oneline_comment(p):
"""
oneline_comment : ONELINECOMMENT
"""
p[0] = p[1].replace("π¬", "#")
def p_comments(p):
"""
comments : comments comment
| comment
"""
p[0] = "".join(p[1:])
def p_nonexecutables(p):
"""
nonexecutables : nonexecutables comments
| nonexecutables newlines
| empty
"""
p[0] = "".join(p[1:])
# PARAMETERS
def p_parameters(p):
"""
parameters : parameters COMMA parameter
| parameter
| empty
"""
p[0] = p[1] + ", " + p[3] if len(p) > 2 else p[1]
def p_class_parameters(p):
"""
class_parameters : parameters
"""
p[0] = f"self, {p[1]}" if len(p[1]) > 1 else "self"
def p_parameter(p):
"""
parameter : simple_parameter
| default_parameter
"""
p[0] = p[1]
def p_simple_parameter(p):
"""
simple_parameter : type IDENTIFIER
"""
global current_scope
current_scope.variables[p[2]] = Variable(p[2], p[1])
p[0] = f"{p[2]}: {p[1]}"
def p_default_parameter(p):
"""
default_parameter : type IDENTIFIER ASSIGN expression
"""
global current_scope
current_scope.variables[p[2]] = Variable(p[2], p[1], p[4])
p[0] = f"{p[2]}: {p[1]} = {p[4]}"
# CLASS
class Class:
def __init__(self, name, cls_fields, fields, constructor, cls_methods, methods):
self.name = name
self.cls_fields = cls_fields
self.fields = fields
self.constructor = constructor
self.cls_methods = cls_methods
self.methods = methods
def __str__(self):
cls_fields = "\n".join(
[f"{field.name}: {field.type}" for field in self.cls_fields]
)
# fields = '\n'.join([f'self.{field.name}: {field.type}' for field in self.fields])
constructor = str(self.constructor) if self.constructor else ""
cls_methods = "\n".join(map(str, self.cls_methods))
methods = "\n".join(map(str, self.methods))
return "\n".join([item for item in [cls_fields, constructor, cls_methods, methods] if item])
def p_class_definition(p):
"""
class_definition : class_naming LBRACE NEWLINE class_body RBRACE NEWLINE
| class_naming INHERITS IDENTIFIER LBRACE NEWLINE class_body RBRACE NEWLINE
"""
global current_scope
match p[2]:
case "π¨βπ¦":
cls: Class = p[6]
cls.name = p[1][1]
classes.append(cls)
p[0] = f"class {p[1][1]}({p[3]}):\n{indent(str(cls))}\n"
case _:
cls: Class = p[4]
cls.name = p[1][1]
classes.append(cls)
p[0] = f"class {p[1][1]}:\n{indent(str(cls))}\n"
current_scope = current_scope.parent
def p_class_naming(p):
"""
class_naming : CLASS IDENTIFIER
"""
global current_scope
if not p[2] in types.keys():
types.update({p[2]: p[2]})
current_scope = ClassScope(p[2], current_scope)
else:
raise PintException("Definition error", f"Class \"{p[2]}\" already defined", p.lexer.lineno, 1, None)
p[0] = (p[1], p[2])
def p_class_body(p):
"""
class_body : nonexecutables fields_declarations nonexecutables constructor_definition nonexecutables methods_definitions nonexecutables
"""
def split_list_by(l, p):
yes, no = [], []
for i in l:
(yes if p(i) else no).append(i)
return yes, no
fields_declarations = p[2]
fields_declarations = split_list_by(
fields_declarations, lambda field: field.is_cls_field
)
constructor_definition = p[4]
methods_definitions = p[6]
methods_definitions = split_list_by(
methods_definitions, lambda method: method.is_cls_method
)
p[0] = Class(
None,
fields_declarations[0],
fields_declarations[1],
constructor_definition,
methods_definitions[0],
methods_definitions[1],
)
def p_fields_declarations(p):
"""
fields_declarations : fields_declarations nonexecutables field_declaration
| field_declaration
| empty
"""
match p[1:]:
case [_, _, _]:
p[0] = [*p[1], p[3]]
case Field():
p[0] = [p[1]]
case _:
p[0] = []
class Field:
def __init__(self, name, type, is_cls_field: bool = False):
self.name = name
self.type = type
self.is_cls_field = is_cls_field
classes = []
def p_field_declaration(p):
"""
field_declaration : type IDENTIFIER NEWLINE
| CLASS type IDENTIFIER NEWLINE
"""
global current_scope
match p[1:]:
case ["ποΈ", _, _, _]:
if current_scope.contains_variable(p[3]):
raise PintException("Definition error", f"Field \"{p[3]}\" already defined in scope {current_scope.name}", p.lexer.lineno, 1, None)
else:
current_scope.variables[p[3]] = Variable(p[3], p[2], None)
p[0] = Field(p[3], p[2], True)
case [_, _, _]:
if current_scope.contains_variable(p[2]):
raise PintException("Definition error", f"Field \"{p[2]}\" already defined in scope {current_scope.name}", p.lexer.lineno - 2, 1, None)
else:
current_scope.variables[p[2]] = Variable(p[2], p[1], None)
p[0] = Field(p[2], p[1])
# CONSTRUCTOR
class Constructor:
def __init__(self, parameters, statements):
self.parameters = parameters
self.statements = statements
def __str__(self):
if self.statements.isspace():
self.statements = "pass"
return f"def __init__({self.parameters}):\n{indent(self.statements)}\n" if self.parameters else f"def __init__(self):\n{indent(self.statements)}\n"
def p_constructor_definition(p):
"""
constructor_definition : constructor_naming LPAREN class_parameters RPAREN LBRACE NEWLINE constructor_body RBRACE NEWLINE
| empty
"""
# @TODO constructor scope
if len(p) > 2:
global current_scope
current_scope = current_scope.parent
p[0] = Constructor(p[3], p[7])
else:
p[0] = ""
def p_constructor_naming(p):
"""
constructor_naming : CONSTRUCTOR IDENTIFIER
"""
global current_scope
current_scope = MethodScope("constructor", current_scope)
p[0] = " ".join(p[1:])
def p_constructor_body(p):
"""
constructor_body : function_body
| function_body super_init_call function_body
"""
p[0] = "".join(p[1:])
def p_super_init_call(p):
"""
super_init_call : INHERITS LPAREN arguments RPAREN
"""
p[0] = f"super().__init__({p[3]})"
# METHODS
class Function:
def __init__(self, name, parameters, return_type, body):
self.name = name
self.parameters = parameters
self.return_type = return_type
self.body = body
def __str__(self):
if self.body is None or self.body.isspace():
self.body = "pass"
return f"def {self.name}({self.parameters}) -> {self.return_type}:\n{indent(self.body)}\n"
class Method(Function):
def __init__(self, name, parameters, return_type, body, is_cls_method: bool = False):
super().__init__(name, parameters, return_type, body)
self.is_cls_method = is_cls_method
def __str__(self):
return f"@classmethod\n{super().__str__()}".replace("self", "cls") if self.is_cls_method else super().__str__()
def p_methods_definitions(p):
"""
methods_definitions : methods_definitions nonexecutables method_definition
| method_definition
| empty
"""
match p[1:]:
case [_, _, _]: