-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLipi Programming Language Interpreter.py
1316 lines (1189 loc) · 46 KB
/
Lipi Programming Language Interpreter.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
# -*- coding: utf-8 -*-
"""
@author: Naman Agarwal
"""
from datetime import datetime
import random, string
##################### Some global initialisations ##########################
# Line no to keep track of what line of code we are on
lineNo = 0
#functions -> name: (start,end)
functions = {}
#start Parenthesis -> start: end
startParenthesis = {}
#end Parenthesis -> end: start
endParenthesis = {}
#A stack full of function objects
functionStack = []
#Time to determine timeout
time = None
# declare array elements
arrayElements = { }
############################## Class Function ###############################
'''
The function class holds -> Name of the fucntion
Start line number of the fucntion
End line number of the fucntion
Variables declared in fucntion and their values
'''
class function:
def __init__(self,Name,Start,End,parameters):
self.start = Start
self.end = End
self.name = Name
self.variables = {}
for arg in parameters:
self.variables[arg[0]] = arg[1]
def print(self):
print("Name -> ", self.name, "\nStart -> ", self.start, " , End -> ", self.end)
print("Variables -> ", self.variables)
################################# Checkers ##################################
def generateRandomVariable():
x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(5))
return x
def isParenthesisWord(word):
li = ["LOOP", "IS", "NONE"]
if word in li:
return True
return False
def isVariable(word):
if len(word)==0:
return False
if word[0] == "$":
j = 0
while j < len(word) and word[j]!="-":
j+=1
if j == len(word):
return True
elif j + 4 == len(word) and word[j+1] == 'l' and word[j+2] == 'e' and word[j+3] == 'n':
return True
else:
return False
return False
def isOperator(word):
# .. -> and
# ++ -> or
# <> -> equal to
# >< -> not equal to
# [] -> absolute value equal to
# ][ -> absolute value not equal to
li = ['+', '-', '*', '/','%',"**","<>",">=","<=",">","<","..","++","><","[]", "][","//"]
if word in li:
return True
return False
def isBracket(word):
li = ['(',')']
if word in li:
return True
return False
def isKeyword(word):
li = ["IN","OUT", "IS", "NONE", "LOOP", "EXIT", "CALL", "RET", "ARR"]
if word in li:
return True
return False
def isNumber(word):
word = str(word)
li = ['0','1','2','3','4','5','6','7','8','9']
dot = False
count = 0
for i in word:
if i in li:
continue
elif i=='.':
if not dot:
dot = True
else:
return False
elif count==0 and i =='-':
return True
else:
return False
count +=1
return True
def isArray(word,obj,ret):
left=""
middle=""
j = 0
while j<len(word) and word[j]!="[":
left = left + word[j]
j+=1
#print(left,middle)
if j>=len(word) or word[j] != "[":
return False
j+=1
while j < len(word) and word[j]!="]":
middle = middle + word[j]
j = j + 1
#print(left,middle)
if j>=len(word) or word[j] != "]" or j+1 != len(word):
return False
if not isVariable(left):
return False
temp = left + "-len"
if isVariable(middle):
if middle in obj.variables.keys():
if temp in obj.variables.keys():
temp = obj.variables.get(temp)
j = 0
left = ""
while j<len(temp) and temp[j]!="-":
left = left + temp[j]
j+=1
temp = left + "-len"
if int(arrayElements.get(temp)) > int(obj.variables.get(middle)) and isNumber(obj.variables.get(middle)):
left = left + "-" + str(int(obj.variables.get(middle)))
else:
raise Exception("Error at " + str(lineNo) + " -> Array not found")
else:
raise Exception("Error at " + str(lineNo) + " -> Index out of bounds" + word)
else:
return False
if ret:
#print(left)
return left
else:
return True
elif isNumber(middle):
if int(middle) >= 0:
if temp in obj.variables.keys():
temp = obj.variables.get(temp)
j = 0
left = ""
while j<len(temp) and temp[j]!="-":
left = left + temp[j]
j+=1
temp = left + "-len"
if arrayElements.get(temp) > int(middle):
left = left + "-" + str(int(middle))
else:
raise Exception("Error at " + str(lineNo) + " -> Index out of bounds")
#print(left,middle)
else:
return False
if ret:
#print(left)
return left
else:
return True
else:
return False
def isArrayLen(word):
length = len(word)
if length < 5:
return False
if word[0]=="$" and word[length-1] == "n" and word[length-2] == "e" and word[length-3] == "l" and word[length-4] == "-":
return True
return False
########################### Initiation of the Code ##########################
'''
Here we recieve the code line by line and we check
where each curly brace starts and where it ends.
We also fill up -> 1. 'functions' dictionary with each function detail
2. 'startParenthesis' dictionary with the start and
corresponding end of each block.
3. 'endParenthesis' dictionary with the end and
corresponding start of each block.
'''
stack = []
def initiate(line,name,type):
global lineNo
words = line.split(" ")
if words[0] == "FN":
if type == None:
type = "FN"
name = words[1]
else:
raise Exception("Error at " + str(lineNo) + " Compile time Error with parenthesis " + words[0])
elif isParenthesisWord(words[0]):
if type==None:
type = words[0]
name = None
else:
raise Exception("Error at " + str(lineNo) + " Compile time Error with parenthesis " + words[0])
elif len(words[0])==1 and words[0]=="{":
if type!=None:
stack.append([type,name,lineNo-1])
name = None
type = None
else:
raise Exception("Error at " + str(lineNo) + " Compile time Error with parenthesis " + words[0])
elif len(words[0])==1 and words[0]=="}":
if type==None and len(stack)!=0:
temp= stack.pop()
if temp[0] == "FN":
if temp[1] not in functions.keys():
functions[temp[1]] = (temp[2],lineNo)
else:
raise Exception("Error at " + str(lineNo) + " Compile time Error -> fucntion overloading not allowed" + words[0])
startParenthesis[temp[2]] = lineNo
endParenthesis[lineNo] = temp[2]
else:
raise Exception("Error at " + str(lineNo) + " Compile time Error with parenthesis " + words[0])
else:
type=None
name=None
return name,type
########################## Evaluatte expressions ############################
#To check the precedence of each operator
def precedence(op):
if op =="++":
return 1
if op == "..":
return 2
if op == "<>" or op=="<" or op==">" or op==">=" or op=="<=" or op=="><" or op=="[]" or op=="][":
return 3
if op == '+' or op == '-':
return 4
if op == '*' or op == '/' or op == '%' or op=="//":
return 5
if op == "**":
return 6
return 0
#To apply the operation of each operator
def applyOp(a, b, op):
if op == '+':
if not isNumber(str(a)) or not isNumber(str(b)):
return str(a) + str(b)
else:
return a + b
if op == '-':
if isNumber(str(a)) and isNumber(str(b)):
return a - b
elif isNumber(str(a)) and a > 0 and a<=len(str(b)):
temp = ""
j = 0
while j < int(a):
temp += str(b)[j]
j+=1
return temp
elif isNumber(str(b)) and b > 0 and b<=len(str(a)):
temp = ""
j = len(str(a)) - int(b)
while j < len(str(a)):
temp += str(a)[j]
j+=1
return temp
else:
raise Exception("Error at " + str(lineNo) + " '-' operator not used correctly on strings")
if op == '*':
if isNumber(str(b)):
return a * b
else:
raise Exception("Error at " + str(lineNo) + " '*' operator not applicable on 2 strings")
if op == '/':
if isNumber(str(a)) and isNumber(str(b)):
return a / b
elif isNumber(str(a)) and a > 0:
if a >= len(str(b)):
return 0
else:
temp = ""
j = int(a)
while j < len(str(b)):
temp = temp + str(b)[j]
j=j+1
return temp
elif isNumber(str(b)) and b > 0:
if b >= len(str(a)):
return 0
else:
temp = ""
i = len(str(a)) - b
j = 0
while j < i:
temp = temp + str(a)[j]
j=j+1
return temp
else:
raise Exception("Error at " + str(lineNo) + " '/' operator not applicable on strings")
if op == "//":
if isNumber(str(a)) and isNumber(str(b)):
return a // b
else:
raise Exception("Error at " + str(lineNo) + " '//' operator not applicable on strings")
if op == '%':
if isNumber(str(a)) and isNumber(str(b)):
return a % b
else:
raise Exception("Error at " + str(lineNo) + " '%' operator not applicable on strings")
if op == "**":
if isNumber(str(a)) and isNumber(str(b)):
return a ** b
else:
raise Exception("Error at " + str(lineNo) + " '**' operator not applicable on strings")
if op == "[]":
if isNumber(str(a)) and isNumber(str(b)):
if abs(a) == abs(b):
return 1
else:
return 0
else:
a = str(a).lower()
b = str(b).lower()
if a == b:
return 1
else:
return 0
if op == "][":
if isNumber(str(a)) and isNumber(str(b)):
if abs(a) != abs(b):
return 1
else:
return 0
else:
a = str(a).lower()
b = str(b).lower()
if a != b:
return 1
else:
return 0
if op == "<>":
if a == b:
return 1
else:
return 0
if op == "><":
if a != b:
return 1
else:
return 0
if op == "<":
if a < b:
return 1
else:
return 0
if op == ">":
if a > b:
return 1
else:
return 0
if op == ">=":
if a >= b:
return 1
else:
return 0
if op == "<=":
if a <= b:
return 1
else:
return 0
if op == "..":
if (a and b):
return 1
else:
return 0
if op == "++":
if (a or b):
return 1
else:
return 0
#To evaluate the infix expression
def evaluate(tokens):
values = []
ops = []
i = 0
while i < len(tokens):
# Current token is a whitespace,
# skip it.
if tokens[i] == ' ':
i += 1
continue
# Current token is an opening
# brace, push it to 'ops'
elif tokens[i] == '(':
ops.append(tokens[i])
# Could be a negtive number or a normal negative sign
elif tokens[i]=='-':
if tokens[i+1] == " ":
# if normal negative sign
tok = tokens[i]
if tokens[i+1]!=" ":
tok = tok + tokens[i+1]
i+=1
while (len(ops) != 0 and
precedence(ops[-1]) >=
precedence(tok)):
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Push current token to 'ops'.
ops.append(tok)
elif tokens[i+1].isdigit():
i=i+1
val = 0
while (i < len(tokens) and
tokens[i].isdigit()):
val = (val * 10) + int(tokens[i])
i += 1
if tokens[i]=='.':
i+=1
flagValue = 0
while (i < len(tokens) and
tokens[i].isdigit()):
val = (val * 10) + int(tokens[i])
flagValue+=1
i += 1
val = val / (10 ** flagValue)
val = val * (-1)
values.append(val)
i=i-1
# Current token is a number, push
# it to stack for numbers.
elif tokens[i].isdigit():
val = 0
# There may be more than one
# digits in the number.
while (i < len(tokens) and
tokens[i].isdigit()):
val = (val * 10) + int(tokens[i])
i += 1
if tokens[i]=='.':
i+=1
flagValue = 0
while (i < len(tokens) and
tokens[i].isdigit()):
val = (val * 10) + int(tokens[i])
flagValue+=1
i += 1
val = val / (10 ** flagValue)
values.append(val)
# right now the i points to
# the character next to the digit,
# since the for loop also increases
# the i, we would skip one
# token position; we need to
# decrease the value of i by 1 to
# correct the offset.
i=i-1
# Closing brace encountered,
# solve entire brace.
elif tokens[i] == ')':
while len(ops) != 0 and ops[-1] != '(':
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# pop opening brace.
ops.pop()
elif tokens[i]=='\"':
text = ""
i+=1
while tokens[i]!='\"':
text = text + tokens[i]
i+=1
#print(text)
values.append(text)
#print(values)
# Current token is an operator.
else:
# While top of 'ops' has same or
# greater precedence to current
# token, which is an operator.
# Apply operator on top of 'ops'
# to top two elements in values stack.
tok = tokens[i]
if tokens[i+1]!=" ":
tok = tok + tokens[i+1]
i+=1
#print(ops)
while (len(ops) != 0 and
precedence(ops[-1]) >=
precedence(tok)):
val2 = values.pop()
val1 = values.pop()
#print(val2,val1)
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Push current token to 'ops'.
ops.append(tok)
i += 1
# Entire expression has been parsed
# at this point, apply remaining ops
# to remaining values.
while len(ops) != 0:
val2 = values.pop()
val1 = values.pop()
#print(val2,val1)
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Top of 'values' contains result,
# return it.
return values[-1]
#To replace all the variables with their values and create a infix equation
def createBool(words,obj,leave):
global lineNo
#print(words)
variables = obj.variables
temp = ""
shouldVariable = True
for i in range(2,len(words)-leave, +1):
if len(words[i]) == 0:
continue
if isVariable(words[i]) and shouldVariable:
shouldVariable = False
wording = words[i]
if isArray(word = wording, obj = obj, ret = False):
wording = isArray(word = wording, obj = obj, ret = True)
#print(wording)
if wording in arrayElements.keys():
if isNumber(str(arrayElements.get(wording))):
temp = temp + str(arrayElements.get(wording)) + " "
else:
temp = temp + "\"" + str(arrayElements.get(wording)) + "\" "
else:
raise Exception("Error at " + str(lineNo) + " -> Variable " + words[i] + " not found")
elif wording in variables.keys():
if isNumber(str(variables.get(wording))):
temp = temp + str(variables.get(wording)) + " "
elif isArrayLen(wording):
temp = temp + str(arrayElements.get(variables.get(wording))) + " "
else:
temp = temp + "\"" + str(variables.get(wording)) + "\" "
else:
raise Exception("Error at " + str(lineNo) + " -> Variable " + words[i] + " not found")
elif isOperator(words[i]) and not shouldVariable:
shouldVariable = True
temp = temp + words[i] + " "
elif isNumber(words[i]) and shouldVariable:
shouldVariable = False
temp = temp + words[i] + " "
elif isBracket(words[i]):
temp = temp + words[i] + " "
elif words[i][0]=="\"":
temp = temp + words[i] + " "
else:
raise Exception("Error at " + str(lineNo) + " -> Expression does not make sense " + words[i])
#print(temp)
return temp
def resizeArray(word,obj,value):
value = int(value)
if value < 0:
raise Exception("Error at " + str(lineNo) + " -> Array size cant be negative")
if word in obj.variables.keys():
prev = obj.variables.get(word)
word = prev
prev = int(arrayElements.get(prev))
wording = ""
j = 0
while j < len(word) and word[j]!="-":
wording+=word[j]
j+=1
if prev == value:
return
elif prev < value:
j = prev
arrayElements[word] = value
while j < value:
text = wording + "-" + str(j)
arrayElements[text] = 0
j+=1
else:
j = value
arrayElements[word] = value
while j < prev:
text = wording + "-" + str(j)
arrayElements.pop(text)
j+=1
else:
raise Exception("Error at " + str(lineNo) + " -> No such array exists")
#To put value into a variable
def addVariable(words,obj):
global lineNo
variables = obj.variables
name = words[0]
#print(name)
if words[1] != '=':
raise Exception("Error at " + str(lineNo) + " -> Equality not found")
temp = createBool(words,obj,0)
#print("temp -> ",temp)
value = evaluate(temp)
if isArray(word = name, obj = obj, ret = False):
name = isArray(word = name, obj = obj, ret = True)
arrayElements[name] = value
return
if isNumber(value) and isArrayLen(words[0]):
resizeArray(words[0],obj,value)
else:
variables[name] = value
############################# Process Keywords ##############################
#find what type of a keyword it is and call the appropreate functions
def processKeyword(words,obj,code):
global lineNo, time
if words[0] == "IN" or words[0] == "OUT":
processIO(words,obj)
return True
elif words[0] == "IS":
processIf(words,obj,code)
return True
elif words[0] == "LOOP":
processLoop(words,obj,code)
return True
elif words[0] == "EXIT":
return processExit(words,obj,code)
elif words[0] == "CALL":
processFucntion(words,obj,code)
return True
elif words[0] == "RET":
return processRet(words, obj, code)
elif words[0] == "ARR":
processArr(words,obj,code)
return True
else:
raise Exception("Error at " + str(lineNo) + " -> Invalid Syntax " + words[0])
#Process the 'IN' and 'OUT' keywords
def processIO(words,obj):
global time
variables = obj.variables
if words[0] == "IN":
i = 1
while i<len(words):
if words[i][0] == "\"":
text = ""
#words[i] = words[i][1:]
word = words[i][1:]
while word[-1]!="\"" and i<len(words):
text = text + word + " "
i+=1
word = words[i]
if i==len(words):
raise Exception("Error at " + str(lineNo) + " -> \" never closed " + words[i])
#words[i] = words[i][:-1]
text = text + word[:-1]
if i+1 == len(words):
raise Exception("Error at " + str(lineNo) + " -> No input asked " + words[i])
print(text, end=" ")
elif isVariable(words[i]):
value = input()
wording = words[i]
if isArray(word = wording, obj = obj, ret = False):
wording = isArray(word = wording, obj = obj, ret = True)
arrayElements[wording] = value
elif isNumber(value) and isArrayLen(wording):
resizeArray(wording,obj,value)
else:
variables[wording] = value
else:
raise Exception("Error at " + str(lineNo) + " -> Invalid Syntax " + words[i])
i+=1
time= datetime.now()
time = time.strftime("%M")
elif words[0] == "OUT":
text = ""
isParanthesis = False
i = 0
#print(words)
for word in words:
#print(word,len(word))
if len(word)==0:
continue
if i!=0:
if isVariable(word) and not isParanthesis:
wording = word
if isArray(word = wording, obj = obj, ret = False):
wording = isArray(word = wording, obj = obj, ret = True)
text = text + str(arrayElements.get(wording)) + " "
elif (wording in variables.keys() and not isArrayLen(wording)):
text = text + str(variables.get(wording)) + " "
elif (wording in variables.keys() and isArrayLen(wording)):
text = text + str(arrayElements.get(variables.get(wording))) + " "
else:
raise Exception("Error at " + str(lineNo) + " -> Invalid Syntax " + words[i])
elif isVariable(word) and isParanthesis:
wording = word
if wording[-1]=="\"":
#print("innnn")
isParanthesis = False
wording = wording[:-1]
text = text + wording + " "
elif isParanthesis:
wording = word
#print("in",word,len(word))
if wording[-1]=="\"":
#print("innnn")
isParanthesis = False
wording = wording[:-1]
text = text + wording + " "
elif not isParanthesis and word[0]=="\"":
isParanthesis = True
wording = word[1:]
if wording[-1]=="\"":
isParanthesis = False
wording = wording[:-1]
text = text + wording + " "
else:
raise Exception("Error at " + str(lineNo) + " -> Invalid Syntax " + words[i])
i+=1
#print(isParanthesis)
if isParanthesis:
raise Exception("Error at " + str(lineNo) + " -> Error with \" " + str(words))
print(text)
#Process the 'IS' and 'NONE' keywords
def processIf(words,obj,code):
global lineNo
text = createBool(words, obj,1)
result = evaluate(text)
if result == 1:
result = True
elif result == 0:
result = False
else:
raise Exception("Error at " + str(lineNo) + " -> Compile time error -> Condition not valid " + code[lineNo])
#print("lineNo -> ",lineNo)
#print(lineNo , " ->-> ",code[lineNo])
if result:
lineNo+=1
#print(lineNo , " ->-> ",code[lineNo])
if lineNo in startParenthesis:
end = startParenthesis.get(lineNo)
#print("Lines -> ",lineNo," ",code[lineNo],end-1," ",code[end-1])
startExecution(mainStart = lineNo, mainEnd=end-1, code=code, obj=obj)
#print("coming out ", code[lineNo])
lineNo = lineNo+1
line = code[lineNo]
if line == "NONE":
#print("in -> ",line)
if (lineNo+1) in startParenthesis.keys():
lineNo = startParenthesis[lineNo+1]
lineNo = lineNo-1
#print("393",lineNo,code[lineNo])
else:
lineNo = lineNo -1
#print(lineNo,code[lineNo])
else:
raise Exception("Error at " + str(lineNo) + " -> Not Indexed Correctly")
else:
lineNo+=1
#print(lineNo , " ->-> ",code[lineNo])
if lineNo in startParenthesis.keys():
lineNo = startParenthesis[lineNo]
#print(lineNo , " ->-> ",code[lineNo])
if code[lineNo] == "NONE":
lineNo+=1
#print(lineNo, "---> ", code[lineNo])
end = startParenthesis.get(lineNo)
#print(end-1, " end = ", code[end-1])
startExecution(mainStart = lineNo, mainEnd = end -1, code = code, obj=obj)
else:
#print(lineNo)
lineNo = lineNo - 1
else:
raise Exception("Error at " + str(lineNo) + " -> Not Indexed Correctly")
#Process the 'LOOP' keyword
def processLoop(words,obj,code):
global lineNo
#print("lno" ,lineNo)
text = createBool(words, obj,1)
result = evaluate(text)
if result == 1:
result = True
elif result == 0:
result = False
else:
raise Exception("Error at " + str(lineNo) + " -> Compile time error -> Condition not valid " + code[lineNo])
#print(result)
continueEndLoop = True
startingPosition = lineNo
while result:
lineNo+=1
#print(lineNo , " ->-> ",code[lineNo])
if lineNo in startParenthesis:
end = startParenthesis.get(lineNo)
#print("Lines -> ",lineNo," ",code[lineNo],end-1," ",code[end-1])
continueEndLoop = startExecution(mainStart = lineNo, mainEnd=end-1, code=code, obj=obj)
#print("coming out ", code[lineNo], " -> ",lineNo)
if not continueEndLoop:
lineNo = startingPosition+1
lineNo = startParenthesis.get(lineNo) -1
return
start = endParenthesis.get(lineNo+1)
lineNo = start-1
#print(lineNo)
text = createBool(words, obj,1)
result = evaluate(text)
if result == 1:
result = True
elif result == 0:
result = False
else:
raise Exception("Error at " + str(lineNo) + " -> Compile time error -> Condition not valid " + code[lineNo])
else:
raise Exception("Error at " + str(lineNo) + " -> Not Indexed Correctly")
if not result:
lineNo = lineNo +1
#print(lineNo)
lineNo = startParenthesis.get(lineNo)
#print(lineNo)
lineNo = lineNo -1
#Process the 'EXIT' keyword
def processExit(words,obj,code):
global lineNo
#print(lineNo)
text = createBool(words, obj,1)
result = evaluate(text)
if result == 1:
#print(False)
return False
elif result == 0:
return True
else:
raise Exception("Error at " + str(lineNo) + " -> Compile time error -> Condition not valid " + code[lineNo])
#Process the 'CALL' keyword
def processFucntion(words,obj,code):
global lineNo
if len(words)==1:
raise Exception("Error at " + str(lineNo) + " -> Fucntion name not given")
if words[1] in functions.keys():
functionLineStart,functionLineEnd = functions.get(words[1])
functionLineStart = functionLineStart -1
#print(functionLineStart,functionLineEnd)
wordFunction = code[functionLineStart]
wordFunction = wordFunction.split(" ")
argumentNeeded = len(wordFunction) - 2
argumentGiving = len(words) - 2
#print(wordFunction)
#print(words)
#print(argumentGiving,argumentNeeded)
if argumentGiving < argumentNeeded:
raise Exception("Error at " + str(lineNo) + " -> Function '" + words[2]+"' needs "+argumentNeeded+" arguments but only "+argumentGiving+"arguments given")
elif argumentGiving == argumentNeeded or (argumentGiving == argumentNeeded + 2 and words[len(words)-2]=="->"):
list = []
for i in range(argumentNeeded):
if isVariable(words[2+i]):
if words[2+i] in obj.variables.keys() and not isArrayLen(words[2+i]):
pair = ( wordFunction[2+i] , obj.variables.get(words[2+i]) )
list.append( pair )
elif isArray(word = words[2+i], obj=obj, ret = False):
wording = isArray(word = words[2+i], obj=obj, ret = True)
if wording in arrayElements.keys():
pair = ( wordFunction[2+i] , arrayElements.get(wording) )
list.append( pair )
else:
raise Exception("Error at " + str(lineNo) + " -> Invalid index for thee array " + words[i+2])
elif isArrayLen(words[2+i]):
if isArrayLen(wordFunction[2+i]):
pair = ( wordFunction[2+i] , obj.variables.get(words[2+i]) )
list.append( pair )
else:
pair = ( wordFunction[2+i] , arrayElements.get(obj.variables.get(words[2+i])) )
list.append( pair )
elif isNumber(words[2+i]):
pair = ( wordFunction[2+i] , words[2+i] )
list.append( pair )
else:
raise Exception("Error at " + str(lineNo) + " -> Invalid argument to the '" + words[2]+"' fucntion call")
FunStart = functions[words[1]]
FunEnd = FunStart[1]
FunStart = FunStart[0]
objectNew = function(words[1],FunStart,FunEnd,list)
functionStack.append(obj)
if len(functionStack) > 31:
#Stack Full after 30 recursive calls
raise Exception("Stack Overflow (Only 31 fucntion calls at a time allowed)")
rememberOldLine = lineNo
returning = startExecution(mainStart = FunStart, mainEnd = FunEnd-1, code = code, obj = objectNew)
lineNo = rememberOldLine
functionStack.pop()
del objectNew
if argumentGiving == argumentNeeded + 2:
if returning == True:
returning = 1
elif returning == False:
returning = 0
if isVariable(words[len(words)-1]):
if isArray(word = words[len(words) -1], obj = obj, ret = False):
wording = isArray(word = words[len(words) -1], obj = obj, ret = True)
if wording in arrayElements.keys():
arrayElements[wording] = returning
else:
raise Exception("Error at -> " + lineNo +" Array index out of bounds " + words[len(words)-1])
else:
obj.variables[words[len(words)-1]] = returning
else:
raise Exception("Error at " + str(lineNo) + " -> "+ words[len(words)-1]+" not a variable")
else:
raise Exception("Error at " + str(lineNo) + " -> Inappropreate number of arguments given to function '" + words[2]+"' ")