forked from devanshusingla/GIPSC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
2392 lines (2038 loc) · 77.4 KB
/
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
from typing import List
from copy import deepcopy
import ply.yacc as yacc
import ply.lex as lex
import lexer
from lexer import *
import sys
import pprint
from scope import *
from utils import *
import os, csv
tokens=lexer.tokens
tokens.remove('COMMENT')
precedence = (
('left', 'LBRACE'),
('right', 'ASSIGN', 'DEFINE'),
('left','IDENT'),
('left','SEMICOLON'),
('left','COLON'),
('left','INT', 'FLOAT', 'IMAG', 'RUNE', 'STRING'),
('left','BREAK'),
('left','CONTINUE'),
('left','RETURN'),
('left', 'COMMA'),
('right', 'NOT', 'ADD_ASSIGN', 'SUB_ASSIGN', 'MUL_ASSIGN', 'QUO_ASSIGN', 'REM_ASSIGN', 'AND_ASSIGN', 'OR_ASSIGN', 'XOR_ASSIGN', 'SHL_ASSIGN', 'SHR_ASSIGN', 'AND_NOT_ASSIGN'),
('left', 'LOR'),
('left', 'LAND'),
('left', 'EQL', 'NEQ','LSS','LEQ','GTR','GEQ'),
('left', 'ADD', 'SUB','OR','XOR'),
('left', 'MUL', 'QUO','REM','AND','AND_NOT','SHL','SHR'),
('left', 'LPAREN', 'RPAREN', 'LBRACK', 'RBRACK', 'RBRACE', 'INC', 'DEC', 'PERIOD'),
('left', 'UMUL'),
)
non_terminals = {}
ignored_tokens = [';', '{', '}', '(', ')', '[', ']', ',']
##################################################################################
#################### ######################
##### STARTING GRAMMAR ########
#################### ######################
##################################################################################
info_tables = {}
stm = SymTableMaker()
target_folder = ''
curr_func_id = 'global'
_symbol = '_'
stm.add(_symbol, {'dataType': {'name': '_', 'baseType': '_', 'level': 0, 'size': 4}})
def p_SourceFile(p):
"""
SourceFile : PackageClause SEMICOLON ImportDeclMult TopLevelDeclMult
"""
# Check if any label has expecting key set
for label in stm.labels:
if stm.labels[label]['expecting'] == True:
assert(len(stm.labels[label]['prevGotos']) > 0)
goto = stm.labels[label]['prevGotos'][0]
raise LogicalError(f"{goto[1]}: Goto declared without declaring any label {label}.")
p[4].children = p[3][1] + p[4].children
p[0] = FileNode(p[1], p[3][0], p[4])
# p[0].code = p[3].code
# p[0].code += p[4].code
###################################################################################
### Package related grammar
###################################################################################
def p_PackageClause(p):
"""
PackageClause : PACKAGE IDENT
"""
p[0] = LitNode(dataType = 'string', label = f'"{p[2]}"')
###################################################################################
### Import related grammar
###################################################################################
def p_ImportDeclMult(p):
"""
ImportDeclMult : ImportDeclMult ImportDecl SEMICOLON
|
"""
if len(p) > 1:
p[1][0].addChild(*p[2][0])
p[1][1].extend(p[2][1])
p[0] = p[1]
else:
p[0] = (ImportNode(), [])
def p_ImportDecl(p):
"""
ImportDecl : IMPORT ImportSpec
| IMPORT LPAREN ImportSpecMult RPAREN
"""
if len(p) == 3:
p[0] = p[2]
elif len(p) == 5:
p[0] = p[3]
def p_ImportMult(p):
"""
ImportSpecMult : ImportSpec SEMICOLON ImportSpecMult
|
"""
if len(p) == 1:
p[0] = ([], [])
elif len(p) == 4:
p[3][0].extend(p[1][0])
p[3][1].extend(p[1][1])
p[0] = p[3]
def p_ImportSpec(p):
"""
ImportSpec : PERIOD ImportPath
| IDENT ImportPath
| ImportPath
"""
global stm, target_folder
if p[1] != '.':
alias = IdentNode(0, p[1][1:-1])
else:
alias = IdentNode(0, p[2][1:-1])
if len(p) == 2:
pathname = getPath(p[1][1:-1]+'.go', target_folder)
path = LitNode(dataType = "string", label = p[1])
else:
pathname = getPath(p[2][1:-1]+'.go', target_folder)
path = LitNode(dataType = "string", label = p[2])
if alias.label in stm.pkgs:
raise NameError(f"{p.lexer.lineno}: Cyclic import not supported")
tmp_target_folder = target_folder
if p[1] != '.':
temp_stm = stm
stm = SymTableMaker()
stm.add(_symbol, {'dataType': {'name': '_', 'baseType': '_', 'level': 0, 'size': 0}})
astNode = buildAndCompile(pathname)
temp_stm.pkgs[alias.label] = stm
stm = temp_stm
p[0] = ([ImportPathNode(alias, path, astNode)], [])
else:
astNode = buildAndCompile(pathname)
stm.pkgs[alias.label] = None
p[0] = (astNode.children[1].children, astNode.children[2].children)
target_folder = tmp_target_folder
def p_ImportPath(p):
"""
ImportPath : STRING
"""
p[0] = p[1]
###################################################################################
### Top-Level related grammar
###################################################################################
def p_TopLevelDeclMult(p):
"""
TopLevelDeclMult : TopLevelDecl SEMICOLON TopLevelDeclMult
|
"""
if len(p)>1:
p[0] = DeclNode()
if isinstance(p[1], list):
p[0].addChild(*p[1])
else:
p[0].addChild(p[1])
p[0].addChild(*p[3].children)
# p[0].code = p[1].code
# p[0].code += p[3].code
if len(p)==1:
p[0] = DeclNode()
def p_TopLevelDecl(p):
"""
TopLevelDecl : Decl
| FuncDecl
"""
if p[1] is not None:
p[0] = p[1]
else:
p[0] = []
def p_Decl(p):
"""
Decl : ConstDecl
| VarDecl
| TypeDecl
"""
if p[1] is not None:
p[0] = p[1]
###################################################################################
### Constant Declarations
###################################################################################
def p_ConstDecl(p):
"""
ConstDecl : CONST ConstSpec
| CONST LPAREN ConstSpecMult RPAREN
"""
if len(p)==3:
p[0] = p[2]
else:
p[0] = p[3]
def p_ConstSpecMult(p):
"""
ConstSpecMult : ConstSpec SEMICOLON ConstSpecMult
| ConstSpec
"""
if len(p) == 4:
p[3].extend(p[1])
p[0] = p[3]
# p[3].code.extend(p[1].code)
# p[0].code = p[3].code
else:
p[0] = []
def p_ConstSpec(p):
"""
ConstSpec : IdentifierList Type ASSIGN ExpressionList
| IdentifierList IDENT ASSIGN ExpressionList
| IdentifierList ASSIGN ExpressionList
"""
p[0] = []
length = len(p)-1
count_0 = 0
count_1 = 0
expression_datatypes = []
# p[0].code =p[1].code
# p[0].code += p[len(p)-1].code
# curr= []
for i in range(len(p[length])):
if isinstance(p[length][i], FuncCallNode):
func_name = p[length][i].children[0].label
dt_return = stm.functions[func_name]["return"]
expression_datatypes.extend(dt_return)
if len(dt_return) == 0:
raise TypeError(f"{p.lexer.lineno}: Function does not return anything!")
elif len(dt_return) == 1:
count_0+=1
else:
count_1+=1
else:
expression_datatypes.append(p[length][i].dataType)
if count_1 > 0:
raise TypeError(f"{p.lexer.lineno}: Functions with multi-valued return type can't be allowed in single-value context!.")
if len(p[length]) > 1:
raise TypeError(f"{p.lexer.lineno}: Function with more than one return values should be assigned alone!")
if len(p[1]) != len(expression_datatypes):
raise NameError(f"{p.lexer.lineno}: Assignment is not balanced")
dt = {}
if len(p) > 4:
if isinstance(p[2], str):
p[2] = stm.findType(p[2])
# if isinstance(p[2], str):
# dt = {'baseType' : p[2], 'name': p[2], 'level': 0}
# dt['size'] = basicTypeSizes[p[2]]
# else:
# dt = p[2].dataType
dt = p[2].dataType
for i, expression in enumerate(expression_datatypes):
#print("Datatypes being compared:", dt, temp)
if not isTypeCastable(stm, dt, expression):
raise TypeError(f"{p.lexer.lineno}: Mismatch of type for identifier: " + p[1][i].label)
if count_1 > 0:
expr = ExprNode(dataType = dt, label = "ASSIGN", operator = "=")
i = 0
for child in p[1]:
expr.addChild(child)
# curr.append([p[1][i], "=" , p[length][i]])
i+=1
expr.addChild(p[length][0])
p[0].append(expr)
else:
i = 0
for (ident, val) in zip(p[1], p[len(p)-1]):
expr = ExprNode(dataType=p[2], label="ASSIGN", operator="=")
expr.addChild(ident, val)
# curr.append([p[1][i], "=" , p[length][i]])
i+= 1
p[0].append(expr)
not_base_type = False
if not isinstance(p[2], str):
not_base_type = True
for i, ident in enumerate(p[1]):
# Check redeclaration for identifier list
latest_scope = stm.getScope(ident.label)
if latest_scope == stm.id or ident.label in stm.functions:
raise NameError(f'{p.lexer.lineno}: Redeclaration of identifier: ' + ident)
if len(p) > 4:
if not not_base_type:
dt = {'baseType' : p[2], 'name': p[2], 'level': 0}
dt['size'] = basicTypeSizes[dt['name']]
else:
dt = p[2].dataType
if not_base_type:
present = checkTypePresence(stm, dt)
else:
present = stm.findType(stm, dt)
if present == -1:
raise TypeError(f'{p.lexer.lineno}: Type not declared/found: ' + dt)
else:
val = None
# Add to symbol table
size = 0
if dt['name'].startswith('int'):
val = int(p[length][i].label)
elif dt['name'].startswith('float'):
val = float(p[length][i].label)
## Write conditions for rune and other types
stm.add(ident.label, {'dataType': dt, 'isConst' : True, 'val': val})
p[1][i].dataType = dt
else:
val = None
dt = p[length][i].dataType
# Add to symbol table
if dt['name'].startswith('int'):
val = int(p[length][i].label)
elif dt['name'].startswith('float'):
val = float(p[length][i].label)
## Write conditions for rune and other types
stm.add(ident.label, {'dataType': dt, 'isConst' : True, 'val': val})
p[1][i].dataType = dt
###################################################################################
### Variable Declarations
###################################################################################
def p_VarDecl(p):
"""
VarDecl : VAR VarSpec
| VAR LPAREN VarMult RPAREN
"""
if len(p)==3:
p[0] = p[2]
else:
p[0] = p[3]
def p_VarMult(p):
"""
VarMult : VarSpec SEMICOLON VarMult
| VarSpec
"""
if len(p) > 1:
p[3].extend(p[1])
p[0] = p[3]
else:
p[0] = [Node()]
def p_VarSpec(p):
"""
VarSpec : IdentifierList Type ASSIGN ExpressionList
| IdentifierList IDENT ASSIGN ExpressionList
| IdentifierList ASSIGN ExpressionList
| IdentifierList Type
| IdentifierList IDENT
"""
p[0] = []
length = len(p)-1
if len(p) >= 4:
count_0 = 0
count_1 = 0
expression_datatypes = []
for i in range(len(p[length])):
if isinstance(p[length][i], FuncCallNode):
func_name = p[length][i].children[0].label
dt_return = stm.functions[func_name]["return"]
expression_datatypes.extend(dt_return)
if len(dt_return) == 0:
raise TypeError(f"{p.lexer.lineno}: Function does not return anything!")
elif len(dt_return) == 1:
count_0+=1
else:
count_1+=1
else:
expression_datatypes.append(p[length][i].dataType)
if count_1 > 0:
if len(p[length]) > 1:
raise TypeError(f"{p.lexer.lineno}: Function with more than one return values should be assigned alone!")
if len(p[1]) != len(expression_datatypes):
raise NameError(f"{p.lexer.lineno}: Assignment is not balanced")
dt = {}
if len(p) > 4:
if isinstance(p[2], str):
p[2] = stm.findType(p[2])
if isinstance(p[2], str):
dt = {'baseType' : p[2], 'name': p[2], 'level': 0}
dt['size'] = basicTypeSizes[p[2]]
else:
dt = p[2].dataType
for i, expression in enumerate(expression_datatypes):
if not isTypeCastable(stm, dt, expression):
raise TypeError(f"{p.lexer.lineno}: Mismatch of type for identifier: " + p[1][i].label)
if count_1 > 0:
expr = ExprNode(dataType = dt, label = "ASSIGN", operator = "=")
for child in p[1]:
expr.addChild(child)
expr.addChild(p[length][0])
p[0].append(expr)
else:
for (ident, val) in zip(p[1], p[len(p)-1]):
expr = ExprNode(dataType=dt, label="ASSIGN", operator="=")
expr.addChild(ident, val)
p[0].append(expr)
not_base_type = False
if not isinstance(p[2], str):
not_base_type = True
for i, ident in enumerate(p[1]):
# Check redeclaration for identifier list
latest_scope = stm.getScope(ident.label)
if latest_scope == stm.id or ident.label in stm.functions:
raise NameError(f'{p.lexer.lineno}: Redeclaration of identifier: ' + ident)
if len(p) > 4:
if not not_base_type:
dt = {'baseType' : p[2], 'name': p[2], 'level': 0}
dt['size'] = basicTypeSizes[p[2]]
else:
dt = p[2].dataType
if not_base_type:
present = checkTypePresence(stm, dt)
else:
present = stm.findType(stm, dt)
if present == -1:
raise TypeError(f'{p.lexer.lineno}: Type not declared/found: ' + dt['name'])
else:
# Add to symbol table
stm.add(ident.label, {'dataType': dt, 'isConst' : False})
p[1][i].dataType = dt
else:
dt = p[length][i].dataType
# Add to symbol table
stm.add(ident.label, {'dataType': dt, 'isConst' : False})
p[1][i].dataType = dt
else:
not_base_type = False
if not isinstance(p[2], str):
not_base_type = True
for i, ident in enumerate(p[1]):
# Check redeclaration for identifier list
latest_scope = stm.getScope(ident.label)
if latest_scope == stm.id or ident.label in stm.functions:
raise NameError(f'{p.lexer.lineno}: Redeclaration of identifier: ' + ident)
if not not_base_type:
dt = {'baseType' : p[2], 'name': p[2], 'level': 0}
dt['size'] = basicTypeSizes[p[2]]
else:
dt = p[2].dataType
if not_base_type:
present = checkTypePresence(stm, dt)
else:
present = stm.findType(dt)
if present == -1:
raise TypeError(f'{p.lexer.lineno}: Type not declared/found: ' + dt)
else:
# Add to symbol table
stm.add(ident.label, {'dataType': dt, 'isConst' : False})
p[1][i].dataType = dt
###################################################################################
### Type Declarations
###################################################################################
def p_TypeDecl(p):
"""
TypeDecl : TYPE TypeSpec
| TYPE LPAREN TypeSpecMult RPAREN
"""
def p_TypeSpecMult(p):
"""
TypeSpecMult : TypeSpec SEMICOLON TypeSpecMult
|
"""
def p_TypeSpec(p):
"""
TypeSpec : AliasDecl
| Typedef
"""
def p_AliasDecl(p):
"""
AliasDecl : IDENT ASSIGN Type
| IDENT ASSIGN IDENT
"""
dt = {}
if isinstance(p[3], str):
dt['name'] = p[3]
dt['baseType'] = p[3]
dt['level'] = 0
else:
dt = p[3].dataType
if checkTypePresence(stm, dt) == -1:
raise TypeError(f"{p.lexer.lineno}: baseType " + dt + " not declared yet")
if p[1] in stm.symTable[stm.id].typeDefs:
raise TypeError(f"{p.lexer.lineno}: Redeclaration of Alias " + p[1])
elif isinstance(p[3], str) and p[3] in stm.symTable[stm.id].avlTypes:
stm.symTable[stm.id].typeDefs[p[1]] = p[3]
elif isinstance(p[3], str):
stm.symTable[stm.id].typeDefs[p[1]] = stm.symTable[stm.id].typeDefs[p[3]]
else:
stm.symTable[stm.id].typeDefs[p[1]] = dt
def p_TypeDef(p):
"""
Typedef : IDENT Type
| IDENT IDENT
"""
if isinstance(p[2], str):
p[2] = stm.findType(p[2])
dt = p[2].dataType
if checkTypePresence(stm, dt) == -1:
raise TypeError(f"{p.lexer.lineno}: baseType " + dt + " not declared yet")
if p[1] in stm.symTable[stm.id].typeDefs:
raise TypeError(f"{p.lexer.lineno}: Redeclaration of type " + p[1])
elif isinstance(p[2], str) and p[2] in stm.symTable[stm.id].avlTypes:
stm.symTable[stm.id].typeDefs[p[1]] = {'baseType': p[2], 'name': p[2], 'level' : 0, 'size': basicTypeSizes[p[2]]}
elif isinstance(p[2], str):
stm.symTable[stm.id].typeDefs[p[1]] = stm.symTable[stm.id].typeDefs[p[2]]
else:
p[2].dataType['baseType'] = p[1]
stm.symTable[stm.id].typeDefs[p[1]] = p[2]
# params = []
# for key in dt['keyTypes']:
# params.append(dt['keyTypes'][key])
# stm.addFunction(p[1], {"params": params , "return": [p[2]], "dataType": {'name': 'func', 'baseType': 'func', 'level': 0}})
###################################################################################
### Identifier List
###################################################################################
def p_IdentifierList(p):
"""
IdentifierList : IDENT
| IDENT COMMA IdentifierList
"""
p[0] = [IdentNode(label = p[1], scope = stm.id)]
if len(p) > 2:
p[0].extend(p[3])
###################################################################################
##################### ######################
###### EXPRESSIONS ########
##################### ######################
###################################################################################
def p_ExpressionList(p):
"""
ExpressionList : Expr
| ExpressionList COMMA Expr
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1]
def p_Expr(p):
"""
Expr : UnaryExpr
| Expr LOR Expr
| Expr LAND Expr
| Expr EQL Expr
| Expr NEQ Expr
| Expr LSS Expr
| Expr LEQ Expr
| Expr GTR Expr
| Expr GEQ Expr
| Expr ADD Expr
| Expr SUB Expr
| Expr OR Expr
| Expr XOR Expr
| Expr MUL Expr
| Expr QUO Expr
| Expr REM Expr
| Expr SHL Expr
| Expr SHR Expr
| Expr AND Expr
| Expr AND_NOT Expr
"""
if len(p) == 2:
p[0] = p[1]
else:
dt1 = p[1].dataType
dt2 = p[3].dataType
firstChar = None
if hasattr(p[3], 'label') and p[3].label != None:
firstChar = p[3].label[0]
if not checkBinOp(stm, dt1, dt2, p[2], firstChar):
raise TypeError(f"{p.lexer.lineno}: Incompatible operand types")
dt = getFinalType(stm, dt1, dt2, p[2])
isConst = False
val = None
if isinstance(p[1], ExprNode) and isinstance(p[3], ExprNode) and p[1].isConst and p[3].isConst:
isConst = True
val = Operate(p[2], p[1].val, p[3].val, p.lexer.lineno, p[3].dataType['name'])
p[0] = ExprNode(operator = p[2], dataType = dt, isConst = isConst, val=val)
p[0].addChild(p[1], p[3])
def p_UnaryExpr(p):
"""
UnaryExpr : PrimaryExpr
| ADD UnaryExpr
| SUB UnaryExpr
| NOT UnaryExpr
| XOR UnaryExpr
| MUL UnaryExpr
| AND UnaryExpr
"""
if len(p) == 2:
p[0] = p[1]
else:
flag = False
if not isinstance(p[2], str) and hasattr(p[2], 'isAddressable'):
flag = p[2].isAddressable
if not checkUnOp(stm, p[2].dataType, p[1], flag):
raise TypeError(f"{p.lexer.lineno}: Incompatible operand for Unary Expression")
val = None
isConst = p[2].isConst
if isConst:
if p[1] == '*' or p[1] == '&':
# Referencing or dereferencing a constant in compile time is not possible
isConst = False
val = None
else:
val = Operate(p[1], None, p[2].val, p.lexer.lineno, p[2].dataType['name'])
isAddressable = flag and (p[1] == '*' or p[1] =='&')
p[0] = ExprNode(dataType = getUnaryType(stm, p[2].dataType, p[1]), operator=p[1], isAddressable = isAddressable, isConst=isConst, val=val)
p[0].addChild(p[2])
###################################################################################
### Primary Expression
###################################################################################
def p_PrimaryExpr(p):
"""
PrimaryExpr : Lit
| IDENT
| LPAREN Expr RPAREN
| PrimaryExpr Selector
| PrimaryExpr Index
| PrimaryExpr Slice
| PrimaryExpr Arguments
"""
## PrimaryExpr -> Lit
if len(p) == 2 and (isinstance(p[1], LitNode) or isinstance(p[1], CompositeLitNode)):
if isinstance(p[1], LitNode):
p[0] = ExprNode(p[1].dataType, p[1].label, None, p[1].isConst, False, p[1].val)
if p[1].children:
for child in p[1].children:
p[0].children.append(child)
else:
# Ig Composite Literal is only used for assignment
p[0] = p[1]
## PrimaryExpr -> Ident
elif (len(p) == 2):
if p[1] in stm.pkgs and stm.pkgs[p[1]] != None:
p[0] = IdentNode(0, p[1], dataType={'name': 'package'})
return
if p[1] in stm.symTable[0].typeDefs:
# Type Declaration Found
# Assuming Constructor Initialisation
dt = stm.symTable[0].typeDefs[p[1]]
p[0] = ExprNode(dataType=dt, label=p[1], isAddressable=False, isConst=False, val=None)
return
# Check declaration
latest_scope = ((stm.getScope(p[1]) != -1) or (p[1] in stm.functions))
if latest_scope == 0:
## To be checked for global declarations (TODO)
print("Expecting global declaration for ",p[1])
stm_entry = stm.get(p[1])
dt = stm_entry['dataType']
p[0] = ExprNode(dataType=dt, label = p[1], isAddressable=True, isConst=stm_entry.get('isConst', False), val=stm_entry.get('val', None))
## PrimaryExpr -> LPAREN Expr RPAREN
elif len(p) == 4:
p[0] = p[2]
else:
dt = None
## PrimaryExpr -> PrimaryExpr Selector
if isinstance(p[2], DotNode):
if isinstance(p[1], IdentNode) and 'name' in p[1].dataType and p[1].dataType['name'] == 'package':
pkg_stm = stm.pkgs[p[1].label]
stm_entry = pkg_stm.get(p[2].children[0])
if stm_entry is None:
raise NameError(f"{p.lexer.lineno}: No such variable or function in package {p[1].label}")
p[0] = ExprNode(dataType=stm_entry['dataType'], label=p[2].children[0], isAddressable=True, isConst=stm_entry.get('isConst', False), val=stm_entry.get('val', None), pkg=p[1].label)
p[0].addChild(p[1],p[2].children[0])
return
if 'name' not in p[1].dataType:
raise TypeError(f"{p.lexer.lineno}: Expecting struct type but found different one")
if stm.findType(p[1].dataType['name']) != -1 or p[1].dataType['name'] == 'struct':
pass
else:
raise TypeError(f"{p.lexer.lineno}: Expecting struct type but found different one")
field = p[2].children[0]
found = False
idx = -1
for i in p[1].dataType['keyTypes']:
if i == field:
found = True
dt = p[1].dataType['keyTypes'][i]
if not found:
raise NameError(f"{p.lexer.lineno}: No such field found in " + p[1].label)
p[2].addChild(p[1])
# dt = p[2].dataType[idx]
## PrimaryExpr -> PrimaryExpr Index
elif isinstance(p[2], IndexNode):
if 'name' not in p[1].dataType or (p[1].dataType['name'] != 'array' and p[1].dataType['name']!= 'map' and p[1].dataType['name'] != 'slice') :
raise TypeError(f"{p.lexer.lineno}: Expecting array or map type but found different one")
if p[1].dataType['name'] == 'array' or p[1].dataType['name'] == 'slice':
if isinstance(p[2].dataType, str):
if not isBasicInteger(stm, p[2].dataType):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].dataType)
else:
if isinstance(p[2].dataType['baseType'], str) and p[2].dataType['level'] == 0:
if not isBasicInteger(stm, p[2].dataType['baseType']):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].dataType)
else:
raise TypeError(f"{p.lexer.lineno}: Index type incorrect")
dt = p[1].dataType.copy()
dt['level']-=1
if dt['level']==0:
dt = {'name': dt['baseType'], 'baseType': dt['baseType'], 'level': 0}
dt['size'] = basicTypeSizes[dt['name']]
if p[1].dataType['name'] == 'map':
if not isTypeCastable(stm, p[2].dataType, p[1].dataType['KeyType']):
raise TypeError(f"{p.lexer.lineno}: Incorrect type for map " + p.lexer.lineno)
dt = p[1].dataType['ValueType']
p[2].children[0] = p[1]
## PrimaryExpr -> PrimaryExpr Slice
elif isinstance(p[2], SliceNode):
if 'name' not in p[1].dataType or (p[1].dataType['name'] != 'slice' and p[1].dataType['name'] != 'array'):
raise TypeError(f"{p.lexer.lineno}: Expecting a slice type but found different one")
if p[2].lIndexNode != None:
if not isBasicInteger(stm, p[2].lIndexNode.dataType['baseType']):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].dataType)
if p[2].rIndexNode != None:
if not isBasicInteger(stm, p[2].rIndexNode.dataType['baseType']):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].dataType)
else:
if isinstance(p[2].lIndexNode.dataType, str):
if not isBasicInteger(stm, p[2].lIndexNode.dataType):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].lIndexNode.dataType)
else:
if isinstance(p[2].lIndexNode.dataType['baseType'], str) and p[2].lIndexNode.dataType['level'] == 0:
if not isBasicInteger(stm, p[2].lIndexNode.dataType):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].lIndexNode.dataType)
else:
raise TypeError(f"{p.lexer.lineno}: Index type incorrect")
if isinstance(p[2].rIndexNode.dataType, str):
if not isBasicInteger(stm, p[2].rIndexNode.dataType):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].rIndexNode.dataType)
else:
if isinstance(p[2].rIndexNode.dataType['baseType'], str) and p[2].rIndexNode.dataType['level'] == 0:
if not isBasicInteger(stm, p[2].rIndexNode.dataType):
raise TypeError(f"{p.lexer.lineno}: Index cannot be of type " + p[2].rIndexNode.dataType)
else:
raise TypeError(f"{p.lexer.lineno}: Index type incorrect")
dt = p[1].dataType.copy()
p[2].children[0] = p[1]
## PrimaryExpr -> PrimaryExpr Arguments
elif isinstance(p[2], List):
if hasattr(p[1], "pkg") and p[1].pkg is not None:
new_stm = stm.pkgs[p[1].pkg]
else:
new_stm = stm
dt = new_stm.findType(p[1].label)
if dt != -1:
if not isinstance(dt, StructType):
raise TypeError(f'Not of type struct')
p[2] = CompositeLitNode(new_stm, dt, p[2])
p[0] = p[2]
p[0].dataType = dt.dataType
p[0].isAddressable = False
return
else:
if p[1].label not in new_stm.functions:
raise NameError(f"{p.lexer.lineno}: No such function declared ")
info = new_stm.functions[p[1].label]
paramList = info['params']
dt = None
if info['return'] != None:
dt = info['return']
if len(paramList) != len(p[2]):
raise NameError(f"{p.lexer.lineno}: Different number of arguments in function call: " + p[1].label + "\n Expected " + str(len(paramList)) + " number of arguments but got " + str(len(p[2])))
for i, argument in enumerate(p[2]):
dt1 = argument.dataType
dt2 = paramList[i]
if not isTypeCastable(new_stm, dt1, dt2):
raise TypeError(f"{p.lexer.lineno}: Type mismatch on argument number: " + i)
p[2] = FuncCallNode(p[1], p[2])
p[0] = p[2]
p[0].isAddressable = True
p[0].dataType = dt
if isinstance(p[2], list):
p[0].isAddressable = False
###################################################################################
## Selector
def p_Selector(p):
"""
Selector : PERIOD IDENT
"""
p[0] = DotNode(p[2])
#########################FuncCallNo##########################################################
## Index
def p_Index(p):
"""
Index : LBRACK Expr RBRACK
"""
p[0] = IndexNode(None, p[2], dataType = p[2].dataType)
###################################################################################
## Slice
def p_Slice(p):
"""
Slice : LBRACK Expr COLON Expr RBRACK
| LBRACK COLON Expr RBRACK
| LBRACK Expr COLON RBRACK
| LBRACK COLON RBRACK
| LBRACK COLON Expr COLON Expr RBRACK
| LBRACK Expr COLON Expr COLON Expr RBRACK
"""
lIndexNode = None
rIndexNode = None
maxIndexNode = None
if len(p) == 5:
if(p[2] == ":"):
rIndexNode = p[3]
else:
lIndexNode = p[2]
elif len(p) == 6:
lIndexNode = p[2]
rIndexNode = p[4]
elif len(p) == 7:
rIndexNode = p[3]
maxIndexNode = p[5]
elif len(p) == 8:
lIndexNode = p[2]
rIndexNode = p[4]
maxIndexNode = p[6]
p[0] = SliceNode(None, lIndexNode, rIndexNode, maxIndexNode)
###################################################################################
## Arguments
def p_Arguments(p):
"""
Arguments : LPAREN RPAREN
| LPAREN ExpressionList RPAREN
| LPAREN ExpressionList COMMA RPAREN
"""
p[0] = []
if len(p) == 4:
if isinstance(p[2], list):
p[0] = p[2]
else:
p[0] = [p[2]]
elif len(p) == 5:
if isinstance(p[2], list):
p[0] = p[2]
else:
p[0] = [p[2]]
###################################################################################
##################### ######################
###### TYPES ########
##################### ######################
###################################################################################
def p_Type(p):
"""
Type : TypeT
| PointerType
| LPAREN PointerType RPAREN
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ParenType(p[2], dataType = p[2].dataType)