-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpl0parser.py
More file actions
1451 lines (1111 loc) · 49.4 KB
/
Copy pathpl0parser.py
File metadata and controls
1451 lines (1111 loc) · 49.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# file: pl0parser.py
# description: PL/0 Parser implementing the PL/0 grammar
# author: Raphael Pour <info@raphaelpour.de>
# date: 24.01.2018
# license: GPL v3 (https://www.gnu.org/licenses/gpl-3.0.en.html)
#
import sys
import os
from enum import Enum
import pprint
import logging
import xmlwriter
from pl0lexer import PL0Lexer, Morphem, MorphemCode, Symbol
from pl0namelist import NLIdent, NLProc, NLConst, NLVar, PL0NameList
from pl0codegen import PL0CodeGen,VMCode
class NonTerminal(Enum):
PROGRAM = 0
BLOCK = 1
EXPRESSION = 2
TERM = 3
STATEMENT = 4
FACTOR = 5
CONDITION = 6
CONSTANT_LIST = 7
CONSTANT_DECLARATION = 8
VARIABLE_LIST = 9
VARIABLE_DECLARATION = 10
PROCEDURE_DECLARATION = 11
ASSIGNMENT_STATEMENT = 12
CONDITIONAL_STATEMENT = 13
LOOP_STATEMENT = 14
COMPOUND_STATEMENT = 15
PROCEDURE_CALL = 16
INPUT_STATEMENT = 17
OUTPUT_STATEMENT = 18
# Compiler Extension
FOR_STATEMENT = 19
PARAMETER_LIST_CALL = 20
PARAMETER_LIST_DECLARATION = 21
ARRAY_INDEX = 22
LOGICAL_EXPRESSION = 23
LOGICAL_TERM = 24
LOGICAL_FACTOR = 25
class EdgeType(Enum):
NIL______ = 0
SYMBOL___ = 1
MORPHEM__ = 2
SUBGRAPH_ = 4
GRAPH_END = 8
class Edge():
def __init__(self, _type, value, emitter, nextEdge, alternativeEdge, nonterminal):
# Also known as Bogen Description
# Use _type to avoid python-keyword-clash
self.type = _type
# Emitter will be implemented later, also known as fx
self.f = emitter
# value is depending on the type a symbol, morphem, subgraph or graph end
self.value = value
# Index of the next Edge, also known as iNext
self.next = nextEdge
# Index of an alternative Edge, also known as iAlt
self.alternative = alternativeEdge
# Stores the current non-terminal for the list lookup
self.nonterminal = nonterminal
def __str__(self):
result = "({:2d},{:2d}) {}".format(
self.next, self.alternative, str(self.type))
if self.type == EdgeType.SYMBOL___:
if(isinstance(self.value, Symbol)):
result += ": " + self.value.name
else:
result += ": " + self.value
elif self.type == EdgeType.MORPHEM__:
result += ": " + self.value.name
elif self.type == EdgeType.SUBGRAPH_:
result += ": " + self.nonterminal.name
return result
class PL0Parser():
def __init__(self, inputFilename, outputFilenname):
# Short identifier for the edge functions
# Program
PR1 = self.programmEnd
# Block
BL1 = self.blockCheckConstIdent
BL2 = self.blockCreateConst
BL3 = self.blockCreateVar
BL4 = self.blockCreateProc
BL5 = self.blockEndProcedure
BL6 = self.blockInitCodeGen
BL7 = self.blockReturnProcedure
# Statement
ST1 = self.statementAssignmentLeftSide
ST2 = self.statementAssignmentRightSide
ST3 = self.statementIfCondition
ST4 = self.statementThenStatement
ST5 = self.statementWhileCondition
ST6 = self.statementWhileAfterCondition
ST7 = self.statementWhileEnd
#ST8 = self.statementCallBeforeParamsProc # Replaced with PL1/PL2
ST9 = self.statementGetVal
ST10 = self.statementPutVal
ST11 = self.statementPutStr
ST12 = self.statementElseKeyword
ST13 = self.statementElseStatement
# Condition
CO1 = self.conditionOdd
CO2 = self.conditionEQ
CO3 = self.conditionNE
CO4 = self.conditionLT
CO5 = self.conditionLE
CO6 = self.conditionGT
CO7 = self.conditionGE
CO8 = self.conditionReleaseCommand
# Expression
EX1 = self.expressionNegSign
EX2 = self.expressionAdd
EX3 = self.expressionSub
TE1 = self.termMul
TE2 = self.termDiv
# Factor
FA1 = self.factorPushNumber
FA2 = self.factorPushIdent
# Language Extension
# For loop
FOR1 = self.forBeforeCondition
FOR2 = self.forBeforeIncrement
FOR3 = self.forAfterIncrement
FOR4 = self.forAfterStatement
# Parameter list
PL1 = self.statementCallBeforeParamsProc
PL2 = self.statementCallAfterParamsProc
PD1 = self.procedureParameter
PD2 = self.procedureEndParameterList
# Array
ARR0 = self.arrayPushAddr
AR1 = self.arraySetIndex
AR2 = self.arrayCrate
AR3 = self.arrayAccess
AR4 = self.arraySwap
FA3 = self.factorGetIdent
ST14= self.statementAssigmnmentIdent
ST15= self.statementGetValIdent
ST16= self.statementGetValToArray
# Logical Expressions
LE1 = self.logicalOr
LT1 = self.logicalNot
LT2 = self.logicalNotAnd
LT3 = self.logicalAnd
# Init Syntax rules
# Short identifier for edge definition
PROG = NonTerminal.PROGRAM
BLCK = NonTerminal.BLOCK
EXPR = NonTerminal.EXPRESSION
TERM = NonTerminal.TERM
STAT = NonTerminal.STATEMENT
FACT = NonTerminal.FACTOR
COND = NonTerminal.CONDITION
CLST = NonTerminal.CONSTANT_LIST
CNST = NonTerminal.CONSTANT_DECLARATION
VLST = NonTerminal.VARIABLE_LIST
VARD = NonTerminal.VARIABLE_DECLARATION
PROC = NonTerminal.PROCEDURE_DECLARATION
ASSS = NonTerminal.ASSIGNMENT_STATEMENT
CNDS = NonTerminal.CONDITIONAL_STATEMENT
LOOP = NonTerminal.LOOP_STATEMENT
COMP = NonTerminal.COMPOUND_STATEMENT
PRCC = NonTerminal.PROCEDURE_CALL
INST = NonTerminal.INPUT_STATEMENT
OUTS = NonTerminal.OUTPUT_STATEMENT
# Language Extension
FORS = NonTerminal.FOR_STATEMENT
PLC = NonTerminal.PARAMETER_LIST_CALL
PLD = NonTerminal.PARAMETER_LIST_DECLARATION
ARR = NonTerminal.ARRAY_INDEX
LEXPR = NonTerminal.LOGICAL_EXPRESSION
LTERM = NonTerminal.LOGICAL_TERM
LFACT = NonTerminal.LOGICAL_FACTOR
programEdges = [
Edge(EdgeType.SUBGRAPH_, BLCK, None, 1, 0, PROG), # 0
Edge(EdgeType.SYMBOL___, '.', PR1, 2, 0, PROG), # 1
# End
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, PROG) # 2
]
constListEdges = [
Edge(EdgeType.SYMBOL___, Symbol.CONST, None, 1, 0, CLST), # 0
Edge(EdgeType.SUBGRAPH_, CNST, None, 2, 0, CLST), # 1
Edge(EdgeType.SYMBOL___, ',', None, 1, 3, CLST), # 2
Edge(EdgeType.SYMBOL___, ';', None, 4, 0, CLST), # 3
# End
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, CLST) # 4
]
constDeclarationEdges = [
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT, BL1, 1, 0, CNST), # 0
Edge(EdgeType.SYMBOL___, '=', None, 2, 0, CNST), # 1
Edge(EdgeType.MORPHEM__, MorphemCode.NUMBER, BL2, 3, 0, CNST), # 2
# End
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, CNST) # 3
]
varListEdges = [
Edge(EdgeType.SYMBOL___, Symbol.VAR, None, 1, 0, VLST), # 0
Edge(EdgeType.SUBGRAPH_, VARD, None, 2, 0, VLST), # 1
Edge(EdgeType.SYMBOL___, ',', None, 1, 3, VLST), # 2
Edge(EdgeType.SYMBOL___, ';', None, 4, 0, VLST), # 3
# End
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, VLST) # 4
]
varDeclarationEdges = [
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT, BL3, 1, 0, VARD), # 0
# Array
Edge(EdgeType.SYMBOL___,'[',None, 2,4, VARD), # 1
Edge(EdgeType.MORPHEM__,MorphemCode.NUMBER,AR1, 3,0, VARD), # 2
Edge(EdgeType.SYMBOL___,']',AR2, 4,0, VARD), # 3
# End
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, VARD) # 4
]
arrayIndexEdges = [
Edge(EdgeType.SYMBOL___,'[',ARR0, 1,0, ARR), # 0
Edge(EdgeType.SUBGRAPH_,EXPR,None, 2,0, ARR), # 1
Edge(EdgeType.SYMBOL___,']',AR3, 3,0, ARR), # 2
# End
Edge(EdgeType.GRAPH_END,0, None, 0,0,ARR) # 3
]
procDeclatationEdges = [
Edge(EdgeType.SYMBOL___, Symbol.PROCEDURE, None, 1, 0, PROC), # 0
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT, BL4, 2, 0, PROC), # 1
Edge(EdgeType.SYMBOL___,'(', None, 3,5,PROC), # 2
Edge(EdgeType.SUBGRAPH_, PLD, None, 4,4, PROC), # 3
Edge(EdgeType.SYMBOL___,')', None, 5,0,PROC), # 4
Edge(EdgeType.SYMBOL___, ';', PD2, 6, 0, PROC), # 5
Edge(EdgeType.SUBGRAPH_, BLCK, None, 7, 0, PROC), # 6
Edge(EdgeType.SYMBOL___, ';', None, 8, 0, PROC), # 7
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, PROC) # 8
]
procedureCallEdges = [
Edge(EdgeType.SYMBOL___, Symbol.CALL, None, 1, 0, PRCC), # 0
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT, PL1, 2, 0, PRCC), # 1
Edge(EdgeType.SYMBOL___,'(', None, 3,5,PRCC), # 2
Edge(EdgeType.SUBGRAPH_, PLC, None, 4,4, PRCC), # 3
Edge(EdgeType.SYMBOL___,')', None, 5,0,PRCC), # 4
Edge(EdgeType.NIL______,0, PL2,6,0,PRCC), # 5
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, PRCC) # 6
]
parameterListCallEdges = [
Edge(EdgeType.SUBGRAPH_, EXPR, None, 1,0,PLC), # 0
Edge(EdgeType.SYMBOL___, ',', None, 0,2, PLC), # 1
Edge(EdgeType.GRAPH_END, 0, None, 0,0, PLC) # 2
]
parameterListDeclarationEdges = [
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT, PD1, 1,0,PLD), # 0
Edge(EdgeType.SYMBOL___, ',', None, 0,2, PLD), # 1
Edge(EdgeType.GRAPH_END, 0, None, 0,0, PLD) # 2
]
assignmentEdges = [
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT,ST14, 1, 0, ASSS), # 0
Edge(EdgeType.SUBGRAPH_,ARR, None,3,2, ASSS), # 1
Edge(EdgeType.NIL______, None, ST1, 3,0, ASSS), # 2
Edge(EdgeType.SYMBOL___, Symbol.ASSIGN, None, 4, 0, ASSS), # 3
Edge(EdgeType.SUBGRAPH_, NonTerminal.EXPRESSION, ST2, 5, 0, ASSS), # 4
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, ASSS) # 5
]
conditionalEdges = [
Edge(EdgeType.SYMBOL___, Symbol.IF, None, 1, 0, CNDS), # 0
Edge(EdgeType.SUBGRAPH_, NonTerminal.LOGICAL_EXPRESSION, ST3, 2, 0, CNDS), # 1
Edge(EdgeType.SYMBOL___, Symbol.THEN, None, 3, 0, CNDS), # 2
Edge(EdgeType.SUBGRAPH_, NonTerminal.STATEMENT, None, 5, 0, CNDS), # 3
Edge(EdgeType.NIL______, None, ST4, 7,0, CNDS), # 4
# ELSE
Edge(EdgeType.SYMBOL___,Symbol.ELSE,ST12, 6,4, CNDS), # 5
Edge(EdgeType.SUBGRAPH_,NonTerminal.STATEMENT, ST13, 7,0,CNDS), # 6
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, CNDS) # 7
]
loopEdges = [
Edge(EdgeType.SYMBOL___, Symbol.WHILE, ST5, 1, 0, LOOP), # 0
Edge(EdgeType.SUBGRAPH_, NonTerminal.LOGICAL_EXPRESSION, ST6, 2, 0, LOOP), # 1
Edge(EdgeType.SYMBOL___, Symbol.DO, None, 3, 0, LOOP), # 2
Edge(EdgeType.SUBGRAPH_, NonTerminal.STATEMENT, ST7, 4, 0, LOOP), # 3
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, LOOP) # 5
]
compoundEdges = [
Edge(EdgeType.SYMBOL___, Symbol.BEGIN, None, 1, 0, COMP), # 0
Edge(EdgeType.SUBGRAPH_, NonTerminal.STATEMENT, None, 2, 0, COMP), # 1
Edge(EdgeType.SYMBOL___, ";", None, 1, 3, COMP), # 2
Edge(EdgeType.SYMBOL___, Symbol.END, None, 4, 0, COMP), # 3
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, COMP) # 4
]
inputEdges = [
Edge(EdgeType.SYMBOL___, "?", None, 1, 0, INST), # 0
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT, ST15, 2, 0, INST), # 1
Edge(EdgeType.SUBGRAPH_, ARR, ST16, 4,3, INST), # 2
Edge(EdgeType.NIL______,None,ST9,4,0,INST), # 3
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, INST) # 4
]
outputEdges = [
Edge(EdgeType.SYMBOL___, "!", None, 1, 0, OUTS), # 0
Edge(EdgeType.MORPHEM__, MorphemCode.STRING, ST11, 3,2, OUTS), # 1
Edge(EdgeType.SUBGRAPH_, NonTerminal.EXPRESSION, ST10, 3, 0, OUTS), # 2
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, OUTS) # 3
]
blockEdges = [
# Constant Declaration
Edge(EdgeType.SUBGRAPH_, CLST, None, 1, 1, BLCK), # 0
# Variable Declaration
Edge(EdgeType.SUBGRAPH_, VLST, None, 2, 2, BLCK), # 1
# Procedure Declaration
Edge(EdgeType.SUBGRAPH_, PROC, None, 2, 3, BLCK), # 2
# Nil Edge (needed for emitter function)
Edge(EdgeType.NIL______, None, BL6, 4, 0, BLCK), # 3
# Statement Declaration
Edge(EdgeType.SUBGRAPH_, STAT, BL5, 5, 0, BLCK), # 4
# End
Edge(EdgeType.GRAPH_END, None, None, 0, 0, BLCK) # 5
]
expressionEdges = [
# Detect negative sign
Edge(EdgeType.SYMBOL___, '-', None, 1, 2, EXPR), # 0
Edge(EdgeType.SUBGRAPH_, TERM, EX1, 3, 0, EXPR), # 1
# No sign detected
Edge(EdgeType.SUBGRAPH_, TERM, None, 3,0, EXPR), # 2
# Detect Add Operation
Edge(EdgeType.SYMBOL___, '+', None, 4, 5, EXPR), # 3
Edge(EdgeType.SUBGRAPH_, TERM, EX2, 3, 0, EXPR), # 4
# Detect Sub Operation
Edge(EdgeType.SYMBOL___, '-', None, 6, 7, EXPR), # 5
Edge(EdgeType.SUBGRAPH_, TERM, EX3, 3, 0, EXPR), # 6
Edge(EdgeType.GRAPH_END, None, None, 0, 0, EXPR) # 7
]
logicalTermEdges = [
# not LTerm
Edge(EdgeType.SYMBOL___,Symbol.NOT, None, 1,2,LTERM), # 0
Edge(EdgeType.SUBGRAPH_,LFACT, LT1, 3,0,LTERM), # 1
# LTerm (without not)
Edge(EdgeType.SUBGRAPH_,LFACT, None, 3,0,LTERM), # 2
# Or
Edge(EdgeType.SYMBOL___,Symbol.AND, None, 4,7,LTERM), # 3
# Not LTerm
Edge(EdgeType.SYMBOL___,Symbol.NOT, None, 5,6,LTERM), # 4
Edge(EdgeType.SUBGRAPH_,LFACT, LT2, 3,0,LTERM), # 5
# LTerm (Without not)
Edge(EdgeType.SUBGRAPH_,LFACT, LT3,7,0,LTERM), # 6
# Graph end
Edge(EdgeType.GRAPH_END,None,None,0,0,LTERM) # 7
]
logicalExpressionEdges = [
Edge(EdgeType.SUBGRAPH_,LTERM,None, 1,0,LEXPR), # 0
Edge(EdgeType.SYMBOL___,Symbol.OR,None, 2,3,LEXPR), # 1
Edge(EdgeType.SUBGRAPH_,LTERM,LE1, 1,0,LEXPR), # 2
Edge(EdgeType.GRAPH_END,None, None, 0,0,LEXPR) # 3
]
logicalFactorEdges = [
# CONDITION
Edge(EdgeType.SUBGRAPH_,COND,None,4,1,LFACT), # 0
# ( LEXPR )
Edge(EdgeType.SYMBOL___,'{',None,2,0,LFACT), # 1
Edge(EdgeType.SUBGRAPH_,LEXPR,None,3,0,LFACT), # 2
Edge(EdgeType.SYMBOL___,'}',None,4,0,LFACT), # 3
Edge(EdgeType.GRAPH_END, None, None, 0,0, LFACT)
]
statementEdges = [
# A := b
Edge(EdgeType.SUBGRAPH_, NonTerminal.ASSIGNMENT_STATEMENT, None, 9, 1, STAT), # 0
# If-Else
Edge(EdgeType.SUBGRAPH_, NonTerminal.CONDITIONAL_STATEMENT, None, 9, 2, STAT), # 1
# While-Loop
Edge(EdgeType.SUBGRAPH_, NonTerminal.LOOP_STATEMENT, None, 9, 3, STAT), # 2
# BEGIN, END
Edge(EdgeType.SUBGRAPH_, NonTerminal.COMPOUND_STATEMENT, None, 9, 4, STAT), # 3
# Call procedure
Edge(EdgeType.SUBGRAPH_, NonTerminal.PROCEDURE_CALL, None, 9, 5, STAT), # 4
# Get value
Edge(EdgeType.SUBGRAPH_, NonTerminal.INPUT_STATEMENT, None, 9, 6, STAT), # 5
# Print value
Edge(EdgeType.SUBGRAPH_, NonTerminal.OUTPUT_STATEMENT, None, 9, 7, STAT), # 6
# For-Loop
Edge(EdgeType.SUBGRAPH_,NonTerminal.FOR_STATEMENT,None,9,8,STAT), # 7
# Return command
Edge(EdgeType.SYMBOL___,Symbol.RETURN, BL7, 9,0,STAT ), # 8
# End
Edge(EdgeType.GRAPH_END, 0, None, 0, 0, STAT) # 9
]
termEdges = [
Edge(EdgeType.SUBGRAPH_, FACT, None, 1, 0, TERM), # 0
Edge(EdgeType.SYMBOL___, '*', None, 2, 3, TERM), # 1
Edge(EdgeType.SUBGRAPH_, FACT, TE1, 1, 0, TERM), # 2
Edge(EdgeType.SYMBOL___, '/', None, 4, 5, TERM), # 3
Edge(EdgeType.SUBGRAPH_, FACT, TE2, 1, 0, TERM), # 4
# End
Edge(EdgeType.GRAPH_END, None, None, 0, 0, TERM) # 5
]
factorEdges = [
# 0-9
Edge(EdgeType.MORPHEM__, MorphemCode.NUMBER, FA1, 7, 1, FACT), # 0
# ( EXPRESSION )
Edge(EdgeType.SYMBOL___, '(', None, 2, 4, FACT), # 1
Edge(EdgeType.SUBGRAPH_, EXPR, None, 3, 0, FACT), # 2
Edge(EdgeType.SYMBOL___, ')', None, 7, 0, FACT), # 3
# Variable or array
Edge(EdgeType.MORPHEM__, MorphemCode.IDENT, FA3, 5, 0, FACT), # 4
Edge(EdgeType.SUBGRAPH_, ARR, AR4, 7,6, FACT), # 5
Edge(EdgeType.NIL______,None, FA2,7,0,FACT), # 6
# End
Edge(EdgeType.GRAPH_END, None, None, 0, 0, FACT) # 7
]
conditionEdges = [
# ODD
Edge(EdgeType.SYMBOL___, Symbol.ODD, None, 1, 2, COND), # 0
Edge(EdgeType.SUBGRAPH_, EXPR, CO1, 10, 0, COND), # 1
# Comparisson
Edge(EdgeType.SUBGRAPH_, EXPR, None, 3, 0, COND), # 2
Edge(EdgeType.SYMBOL___, '=', CO2, 9, 4, COND), # 3
Edge(EdgeType.SYMBOL___, '#', CO3, 9, 5, COND), # 4
Edge(EdgeType.SYMBOL___, '>', CO6, 9, 6, COND), # 5
Edge(EdgeType.SYMBOL___, '<', CO4, 9, 7, COND), # 6
Edge(EdgeType.SYMBOL___, Symbol.LESSER_EQUAL, CO5, 9, 8, COND), # 7
Edge(EdgeType.SYMBOL___, Symbol.GREATER_EQUAL, CO7, 9, 0, COND), # 8
Edge(EdgeType.SUBGRAPH_, EXPR, CO8, 10, 0, COND), # 9
# End
Edge(EdgeType.GRAPH_END, None, None, 0, 0, COND) # 10
]
forEdges = [
Edge(EdgeType.SYMBOL___, Symbol.FOR, None, 1,0,FORS), # 0
Edge(EdgeType.SYMBOL___, '(', None, 2,0,FORS), # 1
Edge(EdgeType.SUBGRAPH_,ASSS,None, 3,0,FORS), # 2
Edge(EdgeType.SYMBOL___,';',FOR1, 4,0,FORS), # 3
Edge(EdgeType.SUBGRAPH_,LEXPR,FOR2,5,0,FORS), # 4
Edge(EdgeType.SYMBOL___,';',None,6,0,FORS), # 5
Edge(EdgeType.SUBGRAPH_,ASSS,FOR3,7,0,FORS), # 6
Edge(EdgeType.SYMBOL___,')', None, 8,0,FORS), # 7
Edge(EdgeType.SUBGRAPH_,STAT,FOR4, 9,0,FORS), # 8
Edge(EdgeType.GRAPH_END,None,None,0,0,FORS) # 9
]
self.edges = {
PROG: programEdges, # 0
BLCK: blockEdges, # 1
EXPR: expressionEdges, # 2
TERM: termEdges, # 3
STAT: statementEdges, # 4
FACT: factorEdges, # 5
COND: conditionEdges, # 6
CLST: constListEdges, # 7
CNST: constDeclarationEdges, # 8
VLST: varListEdges, # 9
VARD: varDeclarationEdges, # 10
PROC: procDeclatationEdges, # 11
ASSS: assignmentEdges, # 12
CNDS: conditionalEdges, # 13
LOOP: loopEdges, # 14
COMP: compoundEdges, # 15
PRCC: procedureCallEdges, # 16
INST: inputEdges, # 17
OUTS: outputEdges, # 18
# Language Extension
FORS: forEdges, # 19
PLC : parameterListCallEdges, # 20
PLD : parameterListDeclarationEdges, # 21
ARR : arrayIndexEdges, # 22
LEXPR : logicalExpressionEdges, # 23
LTERM : logicalTermEdges, # 24
LFACT : logicalFactorEdges
}
# Init Lexer
self.inputFilename = inputFilename
self.lexer = PL0Lexer(self.inputFilename)
# Init NameList
self.nameList = PL0NameList()
self.currentIdent = None
self.currentIndex = 0
# Init Code Generator
self.outputFilename = outputFilenname
self.codeGen = PL0CodeGen(self.outputFilename)
def parse(self, edge=None, path=[]):
morphemProcessed = False
localPath = []
success = False
# Initialize Parser if we are called for the first time
if self.lexer.morphem.code == MorphemCode.EMPTY:
self.lexer.lex()
if not edge:
startEdge = self.edges[NonTerminal.PROGRAM][0]
startList = [{
'value': str(startEdge.nonterminal.name),
'type': EdgeType.SUBGRAPH_,
'pos': (self.lexer.morphem.lines, self.lexer.morphem.cols),
'sub': []
}]
result = self.parse(startEdge, startList)
if result:
startList[0]['sub'] = result
return startList
else:
return False
while True:
# Check Edge type
# Symbol detected -> Syntactically right Symbol?
if edge.type == EdgeType.SYMBOL___:
success = self.lexer.morphem.value == edge.value
if success:
localPath.append({
'value': self.lexer.morphem.value,
'type': edge.type,
'pos': (self.lexer.morphem.lines, self.lexer.morphem.cols)})
# Morphem detected -> Syntacticaly right morphem?
elif edge.type == EdgeType.MORPHEM__:
success = self.lexer.morphem.code == edge.value
if success:
localPath.append({
'value': self.lexer.morphem.value,
'type': edge.type,
'pos': (self.lexer.morphem.lines, self.lexer.morphem.cols)
})
# Subgraph detected -> Go deeper
elif edge.type == EdgeType.SUBGRAPH_:
nextEdge = self.edges[edge.value][0]
localPath.append({
'value': nextEdge.nonterminal.name,
'type': EdgeType.SUBGRAPH_,
'pos': (self.lexer.morphem.lines, self.lexer.morphem.cols),
'sub': []
})
result = self.parse(nextEdge, path + localPath)
if result:
success = True
# Combines the local parse tree with the deeper one
# This allows to ignore the delivered path argument
localPath[-1]['sub'] = result
else:
success = False
# Delete the subgraph from the local Path because it wasn't
# successful
localPath.pop()
# End detected -> Return the current parse-tree
elif edge.type == EdgeType.GRAPH_END:
return localPath
elif edge.type == EdgeType.NIL______:
success = True
# Call Emitter
if success and edge.f:
success = edge.f()
if success is None:
logging.error("[Parser] Missing valid return value of edge function {}(). It returned with None".format(edge.f.__name__))
# Check alternatives if evaluation of edge type
# wasn't successful
if not success:
if edge.alternative != 0:
edge = self.edges[edge.nonterminal][edge.alternative]
elif morphemProcessed:
logging.error("[Parser] Syntax Error near {}:{}: {}".format(
self.lexer.morphem.lines,
self.lexer.morphem.cols,
self.lexer.morphem.value))
errorEdge = {
'value': "ERROR",
'type': EdgeType.NIL______,
'pos': (self.lexer.morphem.lines, self.lexer.morphem.cols)
}
localPath.append(errorEdge)
x = xmlwriter.XMLWriter("error.xml")
x.writeAll(localPath)
sys.exit(1)
else:
# It's BACKTRACKIN' TIME
return False
else:
# Accept morphem
if edge.type in [EdgeType.SYMBOL___, EdgeType.MORPHEM__]:
self.lexer.lex()
edge = self.edges[edge.nonterminal][edge.next]
morphemProcessed = True
return localPath
#
# EDGE FUNCTIONS
#
# PROGRAM
# Also known as Pr1
def programmEnd(self):
# Write the count of procedures at the very beginning
self.codeGen.setTotalCountOfProcedures(len(self.nameList.procedures))
# Append List of constants to the end of the file before
# closing it
self.codeGen.writeConstList(self.nameList.constantList)
self.codeGen.closeOutputfile()
return True
# BLOCK
# Also known as BL1
def blockCheckConstIdent(self):
# Get ident by current morphem
constIdent = str(self.lexer.morphem.value)
# Create Constant, print error if locally existing
if self.nameList.isLocalIdentName(constIdent):
logging.error("[Parser] Can't create Const-Ident: Ident {} already existing.".format(constIdent))
# Error-Handling
return False
self.currentIdent = constIdent
return True
# Also known as BL2
def blockCreateConst(self):
# Check if current ident is set in order to add a new
# constant to the namelist
if self.currentIdent is None:
logging.error("[Parser] Ident must be set before setting the value")
return False
# Get the value from our current morphem
value = int(self.lexer.morphem.value)
# Add Constant to our namelist
self.nameList.createConst(name=self.currentIdent,value=value)
# Reset ident to None in order to avoid errors
self.currentIdent = None
return True
# Also known as BL3
def blockCreateVar(self):
# Check if ident is already defined in local scope
ident = str(self.lexer.morphem.value)
# Create Constant, print error if locally existing
if self.nameList.isLocalIdentName(ident):
logging.error("[Parser] Can't create Var-Ident: Ident {} already existing.".format(ident))
# Error-Handling
return False
self.currentIdent = ident
# Add Variable to our namelist
self.nameList.createVar(name=ident)
return True
# Also known as BL4
def blockCreateProc(self):
# Check if ident is already defined in local scope
ident = str(self.lexer.morphem.value)
if self.nameList.isLocalIdentName(ident):
logging.error("[Parser] Can't create Const-Ident: Ident {} already existing.".format(ident))
# Error-Handling
return False
self.nameList.createProc(ident)
return True
def procedureParameter(self):
# Check if ident is already defined in local scope
ident = str(self.lexer.morphem.value)
# Create Constant, print error if locally existing
if self.nameList.isLocalIdentName(ident):
logging.error("[Parser] Can't create Procedure-Parameter-Ident: Ident {} already existing.".format(ident))
# Error-Handling
return False
# Add Variable to our namelist
self.nameList.createProcedureParam(name=ident)
return True
def procedureEndParameterList(self):
# Recalculate the relative addresses of the parameters
# otherwise the first one gets the highest address and
# is used as last parameter
self.nameList.correctParameterList()
return True
def blockReturnProcedure(self):
# Pop all parameters
for _ in filter(lambda v: v.procedureParameter ,self.nameList.currentProcedure.variables):
if not self.codeGen.writeCommand(VMCode.POP):
return False
# Write Return Statement (Doesn't need an address, cause Beck's VM can handle it by itself)
if not self.codeGen.writeCommand(VMCode.RET_PROC):
return False
return True
# Also known as BL5
def blockEndProcedure(self):
# Pop all parameters
for _ in filter(lambda v: v.procedureParameter ,self.nameList.currentProcedure.variables):
if not self.codeGen.writeCommand(VMCode.POP):
return False
# Write Return Statement (Doesn't need an address, cause Beck's VM can handle it by itself)
if not self.codeGen.writeCommand(VMCode.RET_PROC):
return False
# Write length of the current procedure at the very
# beginning
if not self.codeGen.setProcedureLength():
return False
# End current Procedure and reset it to the parrent
if not self.nameList.endProc():
return False
# Write current output buffer to file
self.codeGen.flushBuffer()
return True
# Also known as BL6
def blockInitCodeGen(self):
# Initialize the code generator
self.codeGen.flushBuffer()
# Write EntryProc command to introduce a new procedure
length = 0
index = self.nameList.currentProcedure.index
varMemorySize = self.nameList.currentProcedure.localAddressOffset
args = [length, index, varMemorySize]
return self.codeGen.writeCommand(VMCode.ENTRY_PROC,args)
# STATEMENT
def statementAssigmnmentIdent(self):
self.currentIdent = str(self.lexer.morphem.value)
return True
# Also known as ST1
def statementAssignmentLeftSide(self):
# Use current morphem as ident
identName = self.currentIdent
# Search globally for ident
ident = self.nameList.searchIdentNameGlobal(identName)
# if ident not found -> Semantic Error!
if ident is None:
logging.error("[Parser] Declaration error: Var {} is used in assignment but not declared.".format(identName))
return False
# Check if const or proc -> Semantic error!
if isinstance(ident, NLProc):
logging.error("[Parser] Type error: Excepted Variable but got Procedure {} instead".format(identName))
return False
if isinstance(ident, NLConst):
logging.error("[Parser] Type error: Excepted Variable but got Constant {} instead".format(identName))
return False
# Check if main/local/global variable
displacement = ident.addressOffset
args = [displacement]
if ident.parent == self.nameList.mainProc:
# Main Variable
if not self.codeGen.writeCommand(VMCode.PUSH_ADDRESS_VAR_MAIN,args):
return False
elif ident.parent == self.nameList.currentProcedure:
# Local Scope Variable
if not self.codeGen.writeCommand(VMCode.PUSH_ADDRESS_VAR_LOCAL,args):
return False
else:
# Global scope Variable
args.append(ident.parent.index)
if not self.codeGen.writeCommand(VMCode.PUSH_ADDRESS_VAR_GLOBAL,args):
return False
return True
# Also known as ST2
def statementAssignmentRightSide(self):
# Value and address are on the stack
# and we store the value to the address
return self.codeGen.writeCommand(VMCode.STORE_VAL)
# Also known as ST3
def statementIfCondition(self):
self.codeGen.pushLabel()
return self.codeGen.writeCommand(VMCode.JMP_NOT,[0])
# Also known as ST4
def statementThenStatement(self):
label = self.codeGen.popLabel()
# Add length of jump command (3 bytes)
label.distance -= 3
return self.codeGen.correctJmp(label)
def statementElseKeyword(self):
jmpNotLabel = self.codeGen.popLabel()
# For the current JMP Command
self.codeGen.pushLabel()
if not self.codeGen.writeCommand(VMCode.JMP,[0]):
return False
# Add length of jump command (3 bytes)
#jmpNotLabel.distance += 3
return self.codeGen.correctJmp(jmpNotLabel)
def statementElseStatement(self):
jmpLabel = self.codeGen.popLabel()
jmpLabel.distance -= 3
return self.codeGen.correctJmp(jmpLabel)
# Also known as ST5
def statementWhileCondition(self):
# Generate Label for the jump at the
# end of the loop. The Label has to point
# to the head
self.codeGen.pushLabel()
return True
# Also known as ST6
def statementWhileAfterCondition(self):
# Generate Label to save the position of the jump
# where we have to replace the address later
self.codeGen.pushLabel()
# Generate JumpNot which jumps to the first command
# after the loop if the condition is false
# Use 0 as placeholder for JumpNot
return self.codeGen.writeCommand(VMCode.JMP_NOT,[0])
def statementWhileEnd(self):
# Add jump pointing to the condition of the current while loop
jmpNotRelAddr = self.codeGen.popLabel()
conditionRelAddr = self.codeGen.popLabel()