-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsbml.py
832 lines (585 loc) · 18.2 KB
/
sbml.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
# Jihu Mun
# 111623901
from tokens import *
import ply.lex as lex
import ply.yacc as yacc
import sys
# FUNCTIONS
class Function(): # A FUNCTION DECLARATION
def __init__(self, name, args, block, expr):
self.name = name
self.args = args
self.block = block
self.expr = expr
def execute(self):
# 1. Add the function name to the referencing environment
functions[self.name] = self
# 2. Check for errors
if not type(self.block) == Block:
p_error()
class FunctionCall(): # CALLING A FUNCTION
def __init__(self, name, args):
self.name = name
self.args = args
def evaluate(self):
# 1. Check if the function exists
if not self.name in functions:
semantic_error()
func = functions[self.name]
# 2. Check for number of arguments
if not len(func.args) == len(self.args):
semantic_error()
# 3. Create local referencing environment and add function args to it.
names.insert(0, {})
for i in range(len(self.args)):
names[0][func.args[i]] = self.args[i].evaluate()
# 4. Execute the function block and return the expression
func.block.execute()
return_value = func.expr.evaluate()
names.pop(0)
return return_value
# STATEMENTS
class Assignment():
def __init__(self, var, expr):
self.var = var
self.expr = expr
def execute(self):
result = self.expr.evaluate()
if result is None:
semantic_error()
else:
# Look for the name starting from top of the stack
for i in range(len(names)):
if self.var.name in names[i]:
names[i][self.var.name] = self.expr.evaluate()
return
# If not found, create a binding in the referencing environment
names[0][self.var.name] = self.expr.evaluate()
class AssignmentIndex():
def __init__(self, var, expr):
self.var = var
self.expr = expr
def execute(self):
# self.var is a ListIndexing object
# Get the actual variable to update
self.var.evaluate()
var_name = self.var.indices[0].name
# Try to find var_name in names
scope = 0
found = False
for i in range(len(names)):
if var_name in names[i]:
var_content = names[i][var_name]
found = True
scope = i
break
if not found:
semantic_error()
try:
indices = self.var.indices[1:]
temp = var_content
for i in indices[:-1]:
temp = temp[i]
temp[indices[-1]] = self.expr.evaluate()
except IndexError:
semantic_error()
# Update the variable
names[scope][var_name] = var_content
class Print():
def __init__(self, expr):
self.expr = expr
def execute(self):
print(self.expr.evaluate())
class Block():
def __init__(self, statements):
self.statements = statements
def execute(self):
for s in self.statements:
s.execute()
class If():
def __init__(self, expr, block):
self.expr = expr
self.block = block
def execute(self):
if not type(self.block) == Block:
p_error()
val = self.expr.evaluate()
if not type(val) == bool:
semantic_error()
if val:
self.block.execute()
class IfElse():
def __init__(self, expr, if_block, else_block):
self.expr = expr
self.if_block = if_block
self.else_block = else_block
def execute(self):
if not (type(self.if_block) == Block and type(self.else_block) == Block):
p_error()
val = self.expr.evaluate()
if not type(val) == bool:
semantic_error()
if val:
self.if_block.execute()
else:
self.else_block.execute()
class While():
def __init__(self, expr, block):
self.expr = expr
self.block = block
def execute(self):
if not type(self.block) == Block:
p_error()
while (True):
val = self.expr.evaluate()
if not type(val) == bool:
semantic_error()
if not val:
break
self.block.execute()
# EXPRESSIONS
class Expr():
def __init__(self):
self.parent = None
def evaluate(self):
pass
# DATA TYPES
class Literal(Expr):
def __init__(self, value):
super().__init__()
self.value = value
def evaluate(self):
return self.value
class Variable(Expr):
def __init__(self, name=""):
super().__init__()
self.name = name
def evaluate(self):
for i in range(len(names)):
if self.name in names[i]:
return names[i][self.name]
return None
class MyTuple(Expr):
def __init__(self, expressions=()):
super().__init__()
self.expressions = expressions
def evaluate(self):
result = []
for expr in self.expressions:
result.append(expr.evaluate())
return tuple(result)
class MyList(Expr):
def __init__(self, expressions=[]):
super().__init__()
self.expressions = expressions
def evaluate(self):
result = []
for expr in self.expressions:
result.append(expr.evaluate())
return result
# ARITHMETICS
class Addition(Expr):
def __init__(self, left, right):
super().__init__()
self.left = left
self.right = right
def evaluate(self):
v1 = self.left.evaluate()
v2 = self.right.evaluate()
if (type(v1) == int or type(v1) == float) and (type(v2) == int or type(v2) == float) or (type(v1) == str and type(v2) == str) or (type(v1) == list and type(v2) == list):
return v1 + v2
else:
semantic_error()
class Subtraction2(Expr):
def __init__(self, left, right):
super().__init__()
self.left = left
self.right = right
def evaluate(self):
v1 = self.left.evaluate()
v2 = self.right
# Make sure left value is integer or float
if not (type(v1) == int or type(v1) == float):
p_error()
else:
return v1 - v2
class IntFloatOperation(Expr):
def __init__(self, left, right, type):
super().__init__()
self.left = left
self.right = right
self.type = type
def evaluate(self):
v1 = self.left.evaluate()
v2 = self.right.evaluate()
# Make sure both expressions are integers or floats
if not (type(v1) == int or type(v1) == float):
semantic_error()
if not (type(v2) == int or type(v2) == float):
semantic_error()
else:
if self.type == "SUBTRACTION":
return v1 - v2
elif self.type == "MULTIPLICATION":
return v1 * v2
elif self.type == "DIVISION":
return v1 / v2
elif self.type == "POWER":
return v1 ** v2
class IntDivOperation(Expr):
def __init__(self, left, right, type):
super().__init__()
self.left = left
self.right = right
self.type = type
def evaluate(self):
v1 = self.left.evaluate()
v2 = self.right.evaluate()
if not (type(v1) == int and type(v2) == int):
semantic_error()
else:
if v2 == 0:
semantic_error()
else:
if self.type == "DIVISION":
return v1 // v2
elif self.type == "MODULO":
return v1 % v2
# LIST AND TUPLE STUFF
class ListIndexing(Expr):
def __init__(self, left, right):
super().__init__()
self.left = left
self.right = right
def evaluate(self):
v1 = self.left.evaluate() # Should be list or str
v2 = self.right.evaluate() # Should be int
if not (type(v1) == list or type(v1) == str):
semantic_error()
# Make sure the second expr is an integer
elif not type(v2) == int:
semantic_error()
else:
if v2 < 0 or v2 >= len(v1):
semantic_error()
else:
if type(self.left) == Variable:
self.indices = [self.left] + [self.right.evaluate()]
elif type(self.left) == ListIndexing:
self.indices = self.left.indices + [self.right.evaluate()]
return v1[v2]
class TupleIndexing(Expr):
def __init__(self, left, right):
super().__init__()
self.left = left
self.right = right
def evaluate(self):
v1 = self.left.evaluate() # Should be int
v2 = self.right.evaluate() # Should be tuple
if not (type(v1) == int and type(v2) == tuple):
semantic_error()
else:
index = v1 - 1
if index < 0 or index >= len(v2):
semantic_error()
else:
return v2[index]
class Membership(Expr):
def __init__(self, left, right):
super().__init__()
self.left = left
self.right = right
def evaluate(self):
# Either expr in list or string in string
v1 = self.left.evaluate()
v2 = self.right.evaluate()
if type(v2) == list:
return v1 in v2
elif type(v2) == str and type(v1) == str:
return v1 in v2
else:
semantic_error()
class Cons(Expr):
def __init__(self, left, right):
super().__init__()
self.left = left
self.right = right
def evaluate(self):
v1 = self.left.evaluate() # Anything
v2 = self.right.evaluate() # List
if not type(v2) == list:
semantic_error()
else:
return [v1] + v2
class Not(Expr):
def __init__(self, expr):
super().__init__()
self.expr = expr
def evaluate(self):
v1 = self.expr.evaluate()
if not type(v1) == bool:
semantic_error()
else:
return not v1
class BinaryBooleanOperation(Expr):
def __init__(self, left, right, type):
super().__init__()
self.left = left
self.right = right
self.type = type
def evaluate(self):
v1 = self.left.evaluate()
if not type(v1) == bool:
semantic_error()
if self.type == 'and':
if not v1:
return False
else:
v2 = self.right.evaluate()
if not type(v2) == bool:
semantic_error()
return v2
elif self.type == 'or':
if v1:
return True
else:
v2 = self.right.evaluate()
if not type(v2) == bool:
semantic_error()
return v2
class Comparison(Expr):
def __init__(self, left, right, type):
super().__init__()
self.left = left
self.right = right
self.type = type
def evaluate(self):
v1 = self.left.evaluate()
v2 = self.right.evaluate()
if (type(v1) == int or type(v1) == float) and (type(v2) == int or type(v2) == float) or (type(v1) == str and type(v2) == str):
if self.type == 'ge':
return v1 >= v2
elif self.type == 'gt':
return v1 > v2
elif self.type == 'le':
return v1 <= v2
elif self.type == 'lt':
return v1 < v2
elif self.type == 'eq':
return v1 == v2
elif self.type == 'ne':
return not (v1 == v2)
else:
semantic_error()
# sbml.py
lexer = lex.lex()
# GRAMMAR FOR PARSING
def p_program(p):
'program : functions LBRACE stmts RBRACE'
p[0] = p[1] + p[3]
def p_functions_empty(p):
'functions :'
p[0] = []
def p_functions_nonempty(p):
'functions : function functions'
p[0] = [p[1]] + p[2]
def p_function_noargs(p):
'function : FUNCTION VARIABLE LPAREN RPAREN ASSIGN stmt expr SEMICOLON'
p[0] = Function(p[2], (), p[6], p[7])
def p_function_args(p):
'function : FUNCTION VARIABLE LPAREN VARIABLE args RPAREN ASSIGN stmt expr SEMICOLON'
p[0] = Function(p[2], (p[4],) + p[5], p[8], p[9])
def p_expr_functioncall_noargs(p):
'expr : VARIABLE LPAREN RPAREN'
p[0] = FunctionCall(p[1], ())
def p_expr_functioncall_args(p):
'expr : VARIABLE LPAREN expr exprtail RPAREN'
p[0] = FunctionCall(p[1], (p[3], ) + p[4])
def p_args_empty(p):
'args :'
p[0] = ()
def p_args_nonempty(p):
'args : COMMA VARIABLE args'
p[0] = (p[2],) + p[3]
def p_stmts_empty(p):
'stmts :'
p[0] = []
def p_stmts_nonempty(p):
'stmts : stmt stmts'
p[0] = [p[1]] + p[2]
def p_expr_variable(p):
'expr : VARIABLE'
p[0] = Variable(p[1])
def p_expr_num(p):
'expr : number %prec NUM'
p[0] = Literal(p[1])
def p_number_i(p):
'number : INTEGER'
p[0] = p[1]
def p_number_r(p):
'number : REAL'
p[0] = p[1]
def p_expr_string(p):
'expr : STRING'
p[0] = Literal(p[1])
def p_expr_bool(p):
'expr : BOOLEAN'
p[0] = Literal(p[1])
def p_stmt_assign(p):
'stmt : expr ASSIGN expr SEMICOLON'
if type(p[1]) == ListIndexing:
p[0] = AssignmentIndex(p[1], p[3])
else:
p[0] = Assignment(p[1], p[3])
def p_stmt_print(p):
'stmt : PRINT expr RPAREN SEMICOLON'
p[0] = Print(p[2])
def p_stmt_block(p):
'stmt : LBRACE stmts RBRACE'
p[0] = Block(p[2])
def p_stmt_if(p):
'stmt : IF expr RPAREN stmt %prec IFNORMAL'
p[0] = If(p[2], p[4])
def p_stmt_ifelse(p):
'stmt : IF expr RPAREN stmt ELSE stmt'
p[0] = IfElse(p[2], p[4], p[6])
def p_stmt_while(p):
'stmt : WHILE expr RPAREN stmt'
p[0] = While(p[2], p[4])
def p_expr_paren(p):
'expr : LPAREN expr RPAREN %prec PAREN'
p[0] = p[2]
def p_expr_emptytuple(p):
'expr : LPAREN RPAREN %prec TUPLEINIT'
p[0] = MyTuple()
def p_expr_nonemptytuple(p):
'expr : LPAREN expr COMMA expr exprtail RPAREN %prec TUPLEINIT'
p[0] = MyTuple((p[2], p[4]) + p[5])
def p_exprtail_nonempty(p):
'exprtail : COMMA expr exprtail'
p[0] = (p[2],) + p[3]
def p_exprtail_empty(p):
'exprtail : %prec EXPRTAILEMPTY'
p[0] = ()
def p_expr_tupleindexing(p):
'expr : SHARP LPAREN expr RPAREN expr %prec TUPLEINDEXING'
# Make sure index is an integer
p[0] = TupleIndexing(p[3].value, p[5])
def p_expr_tupleindexing2(p):
'expr : SHARP number expr %prec TUPLEINDEXING'
# Make sure index is an integer
p[0] = TupleIndexing(p[2], p[3])
def p_expr_listindexing(p):
'expr : expr LBRACKET expr RBRACKET %prec LISTINDEXING'
# Make sure first expr is a list or string
p[0] = ListIndexing(p[1], p[3])
def p_expr_emptylist(p):
'expr : LBRACKET RBRACKET %prec LISTINIT'
p[0] = MyList()
def p_expr_nonemptylist(p):
'expr : LBRACKET expr exprtail RBRACKET %prec LISTINIT'
p[0] = MyList([p[2]] + list(p[3]))
def p_expr_exponent(p):
'expr : expr POWER expr'
p[0] = IntFloatOperation(p[1], p[3], type="POWER")
def p_expr_mult(p):
'expr : expr MULT expr'
p[0] = IntFloatOperation(p[1], p[3], type="MULTIPLICATION")
def p_expr_div(p):
'expr : expr DIV expr'
p[0] = IntFloatOperation(p[1], p[3], type="DIVISION")
def p_expr_intdiv(p):
'expr : expr INTDIV expr'
p[0] = IntDivOperation(p[1], p[3], type="DIVISION")
def p_expr_mod(p):
'expr : expr MOD expr'
p[0] = IntDivOperation(p[1], p[3], type="MODULO")
def p_expr_add(p):
'expr : expr ADD expr'
p[0] = Addition(p[1], p[3])
def p_expr_sub(p):
'expr : expr SUB expr'
p[0] = IntFloatOperation(p[1], p[3], 'SUBTRACTION')
def p_number_negation(p):
'number : USUB number %prec UMINUS'
if not (type(p[2]) == int or type(p[2]) == float):
p_error()
else:
p[0] = -p[2]
def p_expr_sub2(p):
'expr : expr USUB number %prec SUBU'
p[0] = Subtraction2(p[1], p[3])
def p_expr_in(p):
'expr : expr IN expr'
p[0] = Membership(p[1], p[3])
def p_expr_cons(p):
'expr : expr CONS expr'
p[0] = Cons(p[1], p[3])
def p_expr_not(p):
'expr : NOT expr'
p[0] = Not(p[2])
def p_expr_and(p):
'expr : expr AND expr'
p[0] = BinaryBooleanOperation(p[1], p[3], 'and')
def p_expr_or(p):
'expr : expr OR expr'
p[0] = BinaryBooleanOperation(p[1], p[3], 'or')
def p_expr_ge(p):
'expr : expr GE expr'
p[0] = Comparison(p[1], p[3], 'ge')
def p_expr_gt(p):
'expr : expr GT expr'
p[0] = Comparison(p[1], p[3], 'gt')
def p_expr_le(p):
'expr : expr LE expr'
p[0] = Comparison(p[1], p[3], 'le')
def p_expr_lt(p):
'expr : expr LT expr'
p[0] = Comparison(p[1], p[3], 'lt')
def p_expr_eq(p):
'expr : expr EQ expr'
p[0] = Comparison(p[1], p[3], 'eq')
def p_expr_ne(p):
'expr : expr NE expr'
p[0] = Comparison(p[1], p[3], 'ne')
def p_error(p=None):
raise ParsingError("SYNTAX ERROR")
def semantic_error():
raise ParsingError("SEMANTIC ERROR")
precedence = (
('right', 'IFNORMAL', 'ELSE'),
('left', 'OR'),
('left', 'AND'),
('left', 'NOT'),
('left', 'GT', 'GE', 'NE', 'EQ', 'LE', 'LT'), # Comparisons
('right', 'CONS'),
('left', 'IN'),
('left', 'ADD', 'SUB', 'SUBU'),
('left', 'MOD', 'INTDIV', 'DIV', 'MULT'),
('right', 'POWER'),
('left', 'EXPRTAILEMPTY'),
('left', 'LISTINDEXING', 'LBRACKET', 'RBRACKET'),
('left', 'ASSIGN'),
('left', 'TUPLEINDEXING'),
('left', 'TUPLEINIT', 'LISTINIT'),
('left', 'PAREN'),
('right', 'UMINUS'),
('left', 'NUM'),
('left', 'INTEGER', 'REAL')
)
parser = yacc.yacc()
# Get the file name
filename = sys.argv[1]
with open(filename) as f:
program = ""
for line in f:
program += line
try:
# Dictionary of names
names = [{}] # This is a stack, with most specific referencing environment coming first
functions = {}
result = parser.parse(program)
for stmt in result:
stmt.execute()
except ParsingError as e:
print(e)