-
Notifications
You must be signed in to change notification settings - Fork 1
/
go_parser.py
1048 lines (819 loc) · 23.1 KB
/
go_parser.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
import sys
from typing import Tuple
from pptree_mod import print_tree
from colorama import Fore, Style
from ply import yacc
import go_lexer
from go_lexer import (
required_tokens_for_parser as tokens,
lex,
find_column,
symtab,
type_table,
)
import utils
from utils import print_error, print_line, print_marker
import syntree
from tac import intermediate_codegen
from ico import optimize_ic
from tree_vis import draw_AST
# def eval_numeric_op(p1, p2=None, op=None):
# if op is None:
# return None
# if p2 is None:
# if is_numeric(p1):
# return Node("numeric", node=(p1.node[0], op(p1.node[1])))
# if is_numeric(p1) and is_numeric(p2):
# if p2.node[0] == p2.node[0]:
# return Node("numeric", node=(p1.node[0], op(p1.node[1], p2.node[1])))
ast = syntree.Node("start", children=[])
precedence = (
# ('left', 'IDENTIFIER'),
# ('left', 'INT', 'BOOL', 'FLOAT64'),
# ('left', '(', ')'),
# ('left', ';'),
# ("right", "WALRUS"),
# ("right", "=", "WALRUS", "ADD_EQ", "SUB_EQ", "MUL_EQ", "DIV_EQ", "MOD_EQ"),
("right", "="),
("left", ","),
("left", "BAR_BAR"),
("left", "AMPER_AMPER"),
("left", "EQ_EQ", "NOT_EQ", "LT", "LT_EQ", "GT", "GT_EQ"),
("left", "+", "-"),
("left", "*", "/", "%"),
("right", "UNARY"),
)
def p_SourceFile(p):
"""SourceFile : PackageClause ';' ImportDeclList TopLevelDeclList"""
ast.data = p[1]
utils.package_name = ast.data
ast.add_child(p[3])
ast.add_child(p[4])
def p_PackageClause(p):
"""PackageClause : KW_PACKAGE PackageName"""
p[0] = p[2][1]
def p_PackageName(p):
"""PackageName : IDENTIFIER"""
p[0] = p[1]
def p_ImportDeclList(p):
"""ImportDeclList : empty
| ImportDecl ';' ImportDeclList
"""
if len(p) == 4:
if p[3] is not None:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = syntree.List([p[1]])
def p_ImportDecl(p):
"""ImportDecl : KW_IMPORT ImportSpec
| KW_IMPORT '(' ImportSpecList ')'
"""
if len(p) == 3:
p[0] = syntree.List([p[2]])
elif len(p) == 5:
p[0] = p[3]
def p_ImportSpecList(p):
"""ImportSpecList : empty
| ImportSpec ';' ImportSpecList
"""
if len(p) == 4:
if p[3] is not None:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = syntree.List([p[1]])
def p_ImportSpec(p):
"""ImportSpec : empty ImportPath
| '.' ImportPath
| PackageName ImportPath
"""
if p[1] is not None:
p[0] = syntree.Import(p[1], p[2])
else:
p[0] = syntree.Import(".", p[2])
def p_ImportPath(p):
"""ImportPath : STRING_LIT"""
p[0] = p[1]
def p_TopLevelDeclList(p):
"""TopLevelDeclList : empty
| TopLevelDecl ';' TopLevelDeclList
"""
if len(p) == 4:
if p[3] is not None:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = syntree.List([p[1]])
def p_TopLevelDecl(p):
"""TopLevelDecl : FunctionDecl
| Declaration
"""
# TODO : Add MethodDecl
p[0] = p[1]
def p_FunctionDecl(p):
"""FunctionDecl : KW_FUNC FunctionName Signature
| KW_FUNC FunctionName Signature FunctionBody
"""
if len(p) == 4:
p[0] = syntree.Function(p[2], p[3], lineno=p.lineno(2))
elif len(p) == 5:
p[0] = syntree.Function(p[2], p[3], body=p[4], lineno=p.lineno(2))
symtab.leave_scope()
def p_FunctionDecl_error(p):
"""FunctionDecl : KW_FUNC FunctionName error
| KW_FUNC FunctionName error FunctionBody
"""
print_error("Error in function declaration")
def p_FunctionName(p):
"""FunctionName : IDENTIFIER"""
p[0] = p[1]
symtab.add_if_not_exists(p[1][1])
syntree.Function.add_func_to_symtab(p[1][1], p.lineno(1))
symtab.enter_scope()
def p_Signature(p):
"""Signature : Parameters
| Parameters Result
"""
if len(p) == 2:
p[0] = syntree.Signature(p[1])
else:
p[0] = syntree.Signature(p[1], p[2])
def p_Parameters(p):
"""Parameters : '(' empty ')'
| '(' ParameterList ')'
| '(' ParameterList ',' ')'
"""
p[0] = p[2]
def p_Result(p):
"""Result : Parameters
| TypeName
| TypeLit
"""
p[0] = p[1]
def p_ParameterList(p):
"""ParameterList : ParameterDecl
| ParameterList ',' ParameterDecl
"""
if len(p) == 4:
p[1].append(p[3])
p[0] = p[1]
elif len(p) == 2:
p[0] = syntree.List([p[1]])
def p_ParameterDecl(p):
"""ParameterDecl : Type
| ELLIPSIS Type
| IdentifierList Type
| IdentifierList ELLIPSIS Type
"""
if len(p) == 2:
p[0] = syntree.ParameterDecl(p[1])
elif len(p) == 3:
if isinstance(p[1], syntree.List):
for ident in p[1]:
ident.add_symtab()
p[0] = syntree.ParameterDecl(p[2], ident_list=p[1])
else:
p[0] = syntree.ParameterDecl(p[2], vararg=True)
elif len(p) == 4:
for ident in p[1]:
ident.add_symtab()
p[0] = syntree.ParameterDecl(p[3], vararg=True, ident_list=p[1])
def p_FunctionBody(p):
"""FunctionBody : Block"""
p[0] = p[1]
def p_Block(p):
"""Block : '{' new_scope StatementList '}' """
p[0] = p[3]
symtab.leave_scope()
def p_new_scope(p):
"""new_scope :"""
symtab.enter_scope()
def p_leave_scope(p):
"""leave_scope :"""
symtab.leave_scope()
def p_StatementList(p):
"""StatementList : empty
| Statement ';' StatementList
"""
if len(p) == 4:
if p[3] is not None:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = syntree.List([p[1]])
def p_Statement(p):
"""Statement : Block
| ReturnStmt
| BreakStmt
| ContinueStmt
| IfStmt
| ForStmt
| SimpleStmt
| Declaration
"""
# TODO : Add more statements like SwitchStmt
p[0] = p[1]
def p_ReturnStmt(p):
"""ReturnStmt : KW_RETURN
| KW_RETURN ExpressionList
"""
if len(p) == 3:
p[0] = syntree.Keyword("RETURN", children=[p[2]], lineno=p.lineno(1))
def p_BreakStmt(p):
"""BreakStmt : KW_BREAK
| KW_BREAK Label
"""
if len(p) == 2:
p[0] = syntree.Keyword("BREAK", lineno=p.lineno(1))
elif len(p) == 3:
p[0] = syntree.Keyword("BREAK", ext=p[2], lineno=p.lineno(1))
def p_Label(p):
"""Label : IDENTIFIER"""
p[0] = p[1]
def p_ContinueStmt(p):
"""ContinueStmt : KW_CONTINUE
| KW_CONTINUE Label
"""
if len(p) == 2:
p[0] = syntree.Keyword("CONTINUE", lineno=p.lineno(1))
elif len(p) == 3:
p[0] = syntree.Keyword("CONTINUE", ext=p[2], lineno=p.lineno(1))
def p_IfStmt(p):
"""IfStmt : KW_IF new_scope Expression Block
| KW_IF new_scope SimpleStmt ';' Expression Block
| KW_IF new_scope Expression Block leave_scope KW_ELSE IfStmt
| KW_IF new_scope Expression Block leave_scope KW_ELSE Block
| KW_IF new_scope SimpleStmt ';' Expression Block leave_scope KW_ELSE IfStmt
| KW_IF new_scope SimpleStmt ';' Expression Block leave_scope KW_ELSE Block
"""
if len(p) == 5:
p[0] = syntree.IfStmt(body=p[4], expr=p[3], lineno=p.lineno(1))
symtab.leave_scope()
elif len(p) == 7:
p[0] = syntree.IfStmt(body=p[6], expr=p[5], statement=p[3], lineno=p.lineno(1))
symtab.leave_scope()
elif len(p) == 8:
p[0] = syntree.IfStmt(body=p[4], expr=p[3], next_=p[7], lineno=p.lineno(1))
elif len(p) == 10:
p[0] = syntree.IfStmt(
body=p[6], statement=p[3], expr=p[5], next_=p[9], lineno=p.lineno(1)
)
def p_ForStmt(p):
"""ForStmt : KW_FOR new_scope Block leave_scope
| KW_FOR new_scope Condition Block leave_scope
| KW_FOR new_scope ForClause Block leave_scope
| KW_FOR new_scope RangeClause Block leave_scope
"""
if len(p) == 5:
p[0] = syntree.ForStmt(
body=p[3], clause=syntree.Literal("bool", "true"), lineno=p.lineno(1)
)
elif len(p) == 6:
p[0] = syntree.ForStmt(body=p[4], clause=p[3], lineno=p.lineno(1))
def p_Condition(p):
"""Condition : Expression"""
p[0] = p[1]
def p_ForClause(p):
"""ForClause : InitStmt ';' ';' PostStmt
| InitStmt ';' Condition ';' PostStmt
"""
if len(p) == 5:
p[0] = syntree.ForClause(
p[1], cond=syntree.Literal("bool", "true"), post=p[4], lineno=p.lineno(1)
)
elif len(p) == 6:
p[0] = syntree.ForClause(p[1], cond=p[3], post=p[5], lineno=p.lineno(1))
def p_InitStmt(p):
"""InitStmt : SimpleStmt"""
p[0] = p[1]
def p_PostStmt(p):
"""PostStmt : SimpleStmt"""
p[0] = p[1]
def p_RangeClause(p):
"""RangeClause : KW_RANGE Expression
| IdentifierList WALRUS KW_RANGE Expression
| ExpressionList '=' KW_RANGE Expression empty
"""
if len(p) == 3:
p[0] = syntree.RangeClause(p[2])
elif len(p) == 5:
for ident in p[1]:
ident.add_symtab()
p[0] = syntree.RangeClause(p[4], ident_list=p[1])
elif len(p) == 6:
p[0] = syntree.RangeClause(p[4], expr_list=p[1])
def p_SimpleStmt(p):
"""SimpleStmt : EmptyStmt
| ExpressionStmt
| IncDecStmt
| Assignment
| ShortVarDecl
"""
p[0] = p[1]
def p_EmptyStmt(p):
"""EmptyStmt : empty"""
def p_ExpressionStmt(p):
"""ExpressionStmt : Expression"""
p[0] = p[1]
def p_IncDecStmt(p):
"""IncDecStmt : Expression INCREMENT
| Expression DECREMENT
"""
p[0] = syntree.UnaryOp(p[2], p[1])
def p_Assignment(p):
"""Assignment : ExpressionList assign_op ExpressionList"""
p[0] = syntree.Assignment(p[2], p[1], p[3], lineno=p.lineno(1))
def p_assign_op(p):
"""assign_op : '='
| ADD_EQ
| SUB_EQ
| MUL_EQ
| DIV_EQ
| MOD_EQ
"""
# # TODO : Add |= ^= <<= >>= &= &^=
p[0] = p[1]
def p_ShortVarDecl(p):
"""ShortVarDecl : IdentifierList WALRUS ExpressionList"""
ident_list = p[1]
for ident in ident_list:
ident.add_symtab()
expr_list = p[3]
p[0] = syntree.make_variable_decls(ident_list, expression_list=expr_list)
def p_Declaration(p):
"""Declaration : VarDecl
| ConstDecl
| TypeDecl
"""
p[0] = p[1]
def p_VarDecl(p):
"""VarDecl : KW_VAR VarSpec
| KW_VAR '(' VarSpecList ')'
"""
if len(p) == 3:
p[0] = syntree.List([p[2]])
elif len(p) == 5:
p[0] = p[3]
def p_VarSpecList(p):
"""VarSpecList : empty
| VarSpec ';' VarSpecList
"""
if len(p) == 4:
if p[3] is not None:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = syntree.List([p[1]])
def p_VarSpec(p):
"""VarSpec : IdentifierList Type
| IdentifierList Type '=' ExpressionList
| IdentifierList '=' ExpressionList
"""
for ident in p[1]:
ident.add_symtab()
if len(p) == 3:
p[0] = syntree.make_variable_decls(p[1], p[2])
elif len(p) == 4:
p[0] = syntree.make_variable_decls(p[1], expression_list=p[3])
elif len(p) == 5:
p[0] = syntree.make_variable_decls(p[1], p[2], p[4])
def p_ConstDecl(p):
"""ConstDecl : KW_CONST ConstSpec
| KW_CONST '(' ConstSpecList ')'
"""
if len(p) == 3:
p[0] = syntree.List([p[2]])
elif len(p) == 5:
p[0] = p[3]
def p_ConstSpecList(p):
"""ConstSpecList : empty
| ConstSpec ';' ConstSpecList
"""
if len(p) == 4:
if p[3] is not None:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = syntree.List([p[1]])
def p_ConstSpec(p):
"""ConstSpec : IdentifierList
| IdentifierList '=' ExpressionList
| IdentifierList Type '=' ExpressionList
"""
for ident in p[1]:
ident.add_symtab()
if len(p) == 2:
p[0] = syntree.make_variable_decls(p[1], const=True)
elif len(p) == 4:
p[0] = syntree.make_variable_decls(p[1], expression_list=p[3], const=True)
elif len(p) == 5:
p[0] = syntree.make_variable_decls(p[1], p[2], p[4], const=True)
def p_TypeDecl(p):
"""TypeDecl : KW_TYPE TypeSpec
| KW_TYPE '(' TypeSpecList ')'
"""
if len(p) == 3:
p[0] = syntree.List([p[2]])
elif len(p) == 5:
p[0] = p[3]
def p_TypeSpecList(p):
"""TypeSpecList : empty
| TypeSpec ';' TypeSpecList
"""
if len(p) == 4:
if p[3] is not None:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = syntree.List([p[1]])
def p_TypeSpec(p):
"""TypeSpec : TypeDef
| AliasDecl
"""
p[0] = p[1]
def p_TypeDef(p):
"""TypeDef : IDENTIFIER Type"""
p[0] = syntree.TypeDef(p[1], p[2], type_table, p.lineno(1))
def p_AliasDecl(p):
"""AliasDecl : IDENTIFIER '=' Type"""
p[0] = syntree.TypeDef(p[1], p[3], type_table, p.lineno(1))
def p_IdentifierList(p):
"""IdentifierList : IDENTIFIER
| IDENTIFIER ',' IdentifierList
"""
if len(p) == 2:
p[0] = syntree.List([syntree.Identifier(p[1], p.lineno(1))])
elif len(p) == 4:
p[3].append(syntree.Identifier(p[1], p.lineno(1)))
p[0] = p[3]
def p_ExpressionList(p):
"""ExpressionList : Expression
| Expression ',' ExpressionList
"""
if len(p) == 4:
p[3].append(p[1])
p[0] = p[3]
elif len(p) == 2:
p[0] = syntree.List([p[1]])
def p_Expression(p):
"""Expression : UnaryExpr
| Expression '+' Expression
| Expression '-' Expression
| Expression '*' Expression
| Expression '/' Expression
| Expression '%' Expression
| Expression EQ_EQ Expression
| Expression NOT_EQ Expression
| Expression LT Expression
| Expression LT_EQ Expression
| Expression GT Expression
| Expression GT_EQ Expression
| Expression BAR_BAR Expression
| Expression AMPER_AMPER Expression
"""
# TODO : Add Logical Operators
# TODO : Add other binary operators
if len(p) == 4:
p[0] = syntree.BinOp(p[2], left=p[1], right=p[3], lineno=p.lineno(2))
else:
p[0] = p[1]
def p_UnaryExpr(p):
"""UnaryExpr : PrimaryExpr
| UnaryOp UnaryExpr
"""
if len(p) == 3:
p[0] = syntree.UnaryOp(p[1], p[2])
else:
# TODO : handle more stuff in PrimaryExpr
# also change the PrimaryExpr class in syntree when doing so
# p[0] = syntree.UnaryOp(None, p[1])
p[0] = p[1]
def p_UnaryOp(p):
"""UnaryOp : '+' %prec UNARY
| '-' %prec UNARY
| '!' %prec UNARY
"""
# TODO : Add other unary operators
p[0] = p[1]
def p_PrimaryExpr(p):
"""PrimaryExpr : Operand
| PrimaryExpr Arguments
| PrimaryExpr Index
"""
# TODO : This is too less! Many more to add
if len(p) == 2:
if isinstance(p[1], syntree.Node):
# p[0] = syntree.PrimaryExpr(operand=None, children=[p[1]])
p[0] = p[1]
else:
p[0] = syntree.PrimaryExpr(operand=p[1])
elif len(p) == 3:
if isinstance(p[2], syntree.Arguments):
p[0] = syntree.FunctionCall(p[1], p[2])
else:
p[0] = syntree.PrimaryExpr(operand=None, children=[p[1], p[2]])
def p_Arguments(p):
"""Arguments : '(' ')'
| '(' ExpressionList ')'
"""
if len(p) == 3:
p[0] = syntree.Arguments(None)
elif len(p) == 4:
p[0] = syntree.Arguments(p[2])
def p_Index(p):
"""Index : '[' Expression ']'"""
p[0] = syntree.Index(p[2])
def p_Operand(p):
"""Operand : OperandName
| Literal
| '(' Expression ')'
"""
if len(p) == 2:
p[0] = p[1]
elif len(p) == 4:
p[0] = p[2]
def p_OperandName(p):
"""OperandName : IDENTIFIER %prec '='
| QualifiedIdent
"""
if not isinstance(p[1], syntree.QualifiedIdent):
ident: Tuple = p[1]
sym = symtab.get_symbol(ident[1])
lineno = p.lineno(1)
if not symtab.is_declared(ident[1]):
print_error()
print(f"Undeclared symbol '{ident[1]}' at line {lineno}")
print_line(lineno)
line: str = utils.lines[lineno - 1]
# TODO: get correct position of token rather than searching
pos = ident[2] - 1
width = len(ident[1])
print_marker(pos, width)
else:
sym.uses.append(lineno)
p[0] = p[1]
def p_QualifiedIdent(p):
"""QualifiedIdent : PackageName '.' IDENTIFIER"""
p[0] = syntree.QualifiedIdent(p[1], p[3])
def p_Literal(p):
"""Literal : BasicLit
| FunctionLit
| CompositeLit"""
# TODO : Add FunctionLit
p[0] = p[1]
def p_CompositeLit(p):
"""CompositeLit : LiteralType LiteralValue"""
p[0] = syntree.Literal(type_=p[1], value=p[2])
def p_LiteralType(p):
"""LiteralType : ArrayType
| '[' '.' '.' '.' ']' ElementType
| TypeName
| SliceType
"""
# TODO: add MapType here
# TODO: add StructType
if len(p) == 2:
p[0] = p[1]
else:
raise NotImplementedError("Array [...] literal not supported yet")
def p_LiteralValue(p):
"""LiteralValue : '{' ElementList '}'"""
if len(p) == 3:
p[0] = None
elif len(p) == 4:
p[0] = p[2]
elif len(p) == 5:
p[0] = p[2]
else:
raise Exception("Bad grammar or rules!")
def p_ElementList(p):
"""ElementList : KeyedElementList"""
if len(p) == 2:
p[0] = p[1]
else:
# p[0] = syntree.List([p[1], *p[2]])
raise Exception("Invalid semantic rules here!")
def p_KeyedElementList(p):
"""KeyedElementList : KeyedElement
| KeyedElement ',' KeyedElementList
"""
if len(p) == 2:
p[0] = syntree.List([p[1]])
elif len(p) == 4:
p[3].append(p[1])
p[0] = p[3]
else:
raise Exception("Bad grammar or rules!")
def p_KeyedElement(p):
"""KeyedElement : Element"""
# TODO: add `Key ':' Element`
if len(p) == 2:
p[0] = p[1]
elif len(p) == 4:
raise Exception("Bad grammar or rules!")
# p[0] = (p[1], p[3])
else:
raise Exception("Bad grammar or rules!")
# def p_Key(p):
# """Key : FieldName
# | Expression
# | LiteralValue
# """
# p[0] = p[1]
# def p_FieldName(p):
# """FieldName : IDENTIFIER
# """
# p[0] = p[1]
def p_Element(p):
"""Element : Expression
| LiteralValue
"""
p[0] = p[1]
def p_BasicLit(p):
"""BasicLit : int_lit
| float_lit
| string_lit
| bool_lit
"""
# TODO : Add other basic literals
p[0] = syntree.Literal(p[1][0], p[1][1])
def p_FunctionLit(p):
"""FunctionLit : KW_FUNC Signature FunctionBody"""
p[0] = syntree.Function(None, p[2], p[3])
def p_int_lit(p):
"""int_lit : INT_LIT"""
# TODO :
# '''int_lit : decimal_lit
# | binary_lit
# | octal_lit
# | hex_lit
# '''
p[0] = p[1]
def p_float_lit(p):
"""float_lit : FLOAT_LIT"""
# TODO :
# '''float_lit : decimal_float_lit
# | hex_float_lit
# '''
p[0] = p[1]
def p_string_lit(p):
"""string_lit : STRING_LIT"""
# TODO :
# '''string_lit : raw_string_lit
# | interpreted_string_lit
# '''
p[0] = p[1]
def p_bool_lit(p):
"""bool_lit : BOOL_LIT"""
p[0] = p[1]
def p_Type(p):
"""Type : TypeName
| TypeLit
| '(' Type ')'
"""
if len(p) == 2:
p[0] = p[1]
elif len(p) == 4:
p[0] = p[2]
def p_TypeName(p):
"""TypeName : BasicType"""
# TODO: QualifiedIdent here gives R/R conflict
if isinstance(p[1], tuple) and p[1][0] == "identifier":
p[0] = p[1][1]
else:
p[0] = p[1]
def p_BasicType(p):
"""BasicType : INT
| INT8
| INT16
| INT32
| INT64
| FLOAT32
| FLOAT64
| UINT
| UINT8
| UINT16
| UINT32
| UINT64
| COMPLEX64
| COMPLEX128
| STRING
| BYTE
| BOOL
| RUNE
"""
p[0] = syntree.Type(name="BasicType", children=[], data=p[1])
def p_TypeLit(p):
"""TypeLit : ArrayType
| PointerType
| FunctionType
| SliceType
"""
# TODO : Add other type literals
# TODO : add StructType
p[0] = p[1]
def p_ArrayType(p):
"""ArrayType : '[' ArrayLength ']' ElementType"""
p[0] = syntree.Array(p[4], p[2])
def p_ArrayLength(p):
"""ArrayLength : Expression"""
p[0] = p[1]
def p_ElementType(p):
"""ElementType : Type"""
p[0] = p[1]
def p_SliceType(p):
"""SliceType : '[' ']' ElementType"""
p[0] = syntree.Slice(p[3])
# def p_StructType(p):
# """StructType : KW_STRUCT '{' FieldDeclList '}' """
# p[0] = syntree.Struct(p[3])
# def p_FieldDeclList(p):
# """FieldDeclList : empty
# | FieldDeclList FieldDecl ';'
# """
# if len(p) == 2:
# p[0] = syntree.List([])
# elif len(p) == 4:
# p[1].append(p[2])
# p[0] = p[1]
# else:
# raise Exception("Invalid grammar?")
# def p_FieldDecl(p):
# """FieldDecl : IdentifierList Type Tag
# | EmbeddedField Tag
# """
# if len(p) == 4:
# p[0] = syntree.StructFieldDecl(p[1], p[2], p[3])
# else:
# p[0] = syntree.StructFieldDecl(p[1], tag=p[2])
# def p_EmbeddedField(p):
# """EmbeddedField : '*' TypeName
# | TypeName"""
# if p[1] == "*":
# p[0] = (p[1], p[2])
# else:
# p[0] = (None, p[1])
# def p_Tag(p):
# """Tag : empty
# | STRING_LIT
# """
# p[0] = p[1]
def p_PointerType(p):
"""PointerType : '*' BaseType"""
def p_BaseType(p):
"""BaseType : Type"""
p[0] = p[1]
def p_FunctionType(p):
"""FunctionType : KW_FUNC Signature"""
def p_empty(p):
"empty :"
pass
def p_error(p: lex.LexToken):
print(f"{Fore.RED}SYNTAX ERROR:{Style.RESET_ALL}")
if p is not None:
col = find_column(p)
print(f"at line {p.lineno}, column {col}")
print_line(p.lineno)
# print(" " * 10, " \t", " " * (col - 1), "^", sep="")
print_marker(col - 1, len(p.value))
else:
print("Unexpected end of file")
parser = yacc.yacc(debug=True)