-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
1938 lines (1424 loc) · 55.9 KB
/
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 -*-
"""
Created on Thu Aug 13 08:48:37 2020
@author: Daniel
Updated 2024-02-26 21:08 EST
"""
version_ = "1.7.3"
"""
to do:
make | its own function, transform ! into argflag3
error handling for local functions ("error in function N" etc.)
make an arg of zero for a for loop stay at zero instead of going negative. [...]_n should loop n times but count backwards
make commands operate on every item in a list if they otherwise don't support lists
i.e. [1,2,3]| +1 p -> [2,3,4]
^ +,-,*,/,e
make f^0 create a virtual machine which is passed the top of the stack and returns the virtual top of the stack, does not affect anything else
"""
"""
new:
better arguments in brackets - (2/3) can now be an argument (including the brackets)
exponentials [done]
iterator in loop!!!!!!!!!!!!!!!!!!!!!!!! [done]
list sum (numerical or string)
negatives (_) (in args as well) (NEEDS TESTING)
strings (take "" as args) [done]
debug function!
make concat use value at pointer if arg is blank (and take argflags to concat backwards)
make loops get value of ~ before going inside loop!
function to go from char to int and vice-versa
make a function to automatically store an array in memory and move the pointer to the next value
make else statements? or maybe just not statements? <-- which can act as else statements (make it use an argflag?)
"""
"""
quick programs:
Fizz&Buzz|!I[g+R1bs%3[0b0b^0]g%5[0b1b^0]B]100 is FizzBuzz - alternatively: Fizz&Buzz|!sSs1S1s2P3[g+R1bs%3[0b1b^0]g%5[0b2b^0]B]100
w is hello world
|[1=q]!-s+>s[g<%~[0=pq]g-s>]~=1p checks to see if input is prime https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime
|[0q][p]0 does this: https://codegolf.stackexchange.com/questions/62732/implement-a-truth-machine
| cat https://codegolf.stackexchange.com/questions/62230/simple-cat-program (note: |p is NOT a cat program, because the input gets parsed when main is not empty)
B&b&uffalo& |I=[b0[2b^b1]b2b3b1b2[3q]b3+]4 does this: https://codegolf.stackexchange.com/questions/218284/output-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo
|IP0[gpP~]0 does this: https://codegolf.stackexchange.com/a/218879/95671
i+R`c0c0$[+i]~ does this: https://codegolf.stackexchange.com/a/219748/95671
|P3 I I^ s =2 s0 [ g0 + s0 g` P2 s =1 /~ s2 g1 P2 +~ s1 ]~ P s =1 /~
^takes a list of resistances in parallel, returns total resistance (AKA harmonic sum)
^example input: [6,3,6]
better prime number checker: |f0;[1=f]-s+>s[g<%~[0=f]g-s>]~=1 <- better because you can actually add code after f0
|s>s[0+q][g-s<*~s>]~ or |I2<[0+q][g-s<*~s>]~ -> factorial (old: |s>-s[0+q][<*~s>g-s]~<g )
"""
"""
For input:
input must come before the | (might not have any |'s)
if you want multiple inputs, use an & as a separator (it will automatically create an array and parse what type everything should be)
if you want to concatenate hard-coded input with user input (or just take only some items as user input), use a \
example: \&potato\&2\ hard-coded and yes&2, es, 4 as user inputs, will give ["yes", 2, "potatoes", 24]
NOTE: there are no escape characters (e.g. \n) or quotation marks (",') that can be taken as input in any way unless you double them.
^if doubled, you can always trim a string by reformatting using R21 to get rid of the excess quotation marks <- e.g. ""test""|R21 --> "test"
"""
import random
#import os
errout_ = ""
output_ = ""
def errorout(str_, end="\n"):
global errout_
errout_ += str(str_) + end
def getError():
global errout_
return(errout_)
def printout(str_, end="\n"):
global output_
output_ += str(str_) + end
class variables():
pass
class localVariables():
pass
class newLocalVariables():
pass
classList = []
v = variables
def parse(code, topLevel = True):
global v
global classList
if(topLevel):
v = variables
else:
#localVariables = copy.deepcopy(newLocalVariables)
#classList.append(copy.deepcopy(localVariables))
classList.append(newLocalVariables())
v = classList[-1]
#v = localVariables
#print(code)
v.loopOrIf = []
v.intoLoopArgs = []
v.loopIterator = []
v.currentFunction = -1
v.currentCommandIndexF = []
v.functionCommandList = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] #this is the limit for no. of fns
#localFunctionCommandList = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] #this is the limit for no. of fns
v.commandsCopyF = v.functionCommandList
v.localFunctions = []
v.inFunction = False
v.endFunctionFlag = False
v.skipTo = []
v.currentCommandIndex = 0
#loopStart = 0
#loopCounter = 0
v.pointer = 0
v.storage = [0] * 100
v.topOfStack = 0
v.loopList = []
v.storedArray = []
v.secondArg = None
v.argFlag = False
v.argFlag2 = False
v.printBuffer = []
v.outputAtEnd = True
v.commandsCopy = None
v.inFunctionList = []
#don't handle errors for now
v.loopListList = []
'''
input|main;function0;function1......functionN:Function0:Function1.....FunctionN [then add arguments here which are stored to a local storage with max of 10000[OLD] values] <-- NOT pushed to stack, separated by ,
if | is the first character, input is taken through input(). If there is a "|", then whatever comes before it is pushed to stack. Otherwise, no input
if the first character in main is a number, then the main method will be repeated that many times (i.e 1main will run twice) -> special case, 0 -> repeats 10 additional times (for 11 times total)
'''
#code = code.replace(" ","")
#split code into input, main, functions, localFunctions:
v.code = code
if(":" in v.code):
temp = v.code.split(":")
v.localFunctions = temp[1:]
v.code = temp[0]
v.pieces = v.code.split(";")
#import re
#pieces = re.split(";|:", code)
#pieces = code.split(";:",str)
v.main = v.pieces[0]
global inputs
try:
if("|" in v.main):
if(v.main.split("|")[0] == ""):
v.topOfStack = inputs.pop(0)
else:
v.topOfStack = v.main.split("|")[0]
v.main = v.main.split("|")[1]#.replace(" ","").replace("\n","")
openString = False
newMain = ""
for char in v.main:
if(char == "\""):
if(not(openString)):
openString = True
else:
openString = False
if((char == " " or char == "\n") and not(openString)):
pass
else:
newMain = newMain + char
v.main = newMain
#print(main)
if(v.main == ""):
printout(v.topOfStack)
return
for char in v.topOfStack:
if(char == '\\'):
v.topOfStack = v.topOfStack.replace("\\", inputs.pop(0),1)
else:
v.outputAtEnd = False
#v.main = v.main.replace(" ","").replace("\n","")
except:
errorout("Input error. Please ensure you have given the program the correct number of inputs!")
return
temp1 = []#auto-parses the input as what it should be
temp2 = None
try:
v.topOfStack =v. topOfStack.split("&")
for elem in v.topOfStack:
try:
exec("a = " + str(elem))
temp2 = locals()["a"]
except:
temp2 = elem
temp1.append(temp2)
v.topOfStack = temp1
if(len(v.topOfStack) == 1):
v.topOfStack = v.topOfStack[0]
except:
try:
exec("a = " + str(v.topOfStack))
v.topOfStack = locals()["a"]
except:
pass
cleanTopOfStack()
v.functions = v.pieces[1::]
#for i in range(len(v.functions)):
#v.functions[i] = v.functions[i].replace(" ","")
try:
repeat = int(v.main[0])
v.main = v.main[1::]
if(v.repeat == 0):
v.repeat = 10
v.repeat = v.repeat + 1
except:
v.repeat = 1
v.commands = getCommandList(v.main,v.repeat)
v.commandsCopy = getCommandList(v.main, v.repeat)
#print(topOfStack, main, functions, repeat, commands)
#run commands.......
#for command in commands: #swap commented lines later
#try:
# runCommand(command)
#except:
# pass
#runCommand(command)
from time import perf_counter as currentTime
start = currentTime()
v.firstError = True
while(v.currentCommandIndex < len(v.commands)):
try:
runCommand(v.commands[v.currentCommandIndex])
except Exception as error:
error_string = str(error)
errorout("Error: " + error_string + " at command index " + str(v.currentCommandIndex) + " [" + str(v.commands[v.currentCommandIndex]) + "]")
if(running):
global output_
global errout_
print(output_)
print(errout_)
raise(error)
return
v.currentCommandIndex += 1
#print("HERE!!!")
if(currentTime() > start + 4):
printout("Program timed out. Did you forget your exit condition?")
errorout("timeout")
return
if(topLevel):
#check for end flags: no output, output last character, etc
if(v.printBuffer != []):
printout("".join(v.printBuffer))
elif(v.outputAtEnd):
printout(v.topOfStack)
def getCommandList(f, rep):
#f.replace("\n","")
possibleArgs = "0123456789~`@&^?._#()\\"# & represents a spacer in case some functions need lots of arguments
#^ and ? are argument flags
tempList = []
last = ""
closed = True
closedRoundBracket = True
for i in range(len(f)):
if(f[i] == "\"" and closed): #let strings exist as args
closed = False
elif(closed == False):
if(not(f[i] == "\"")):
tempList[-1] = last + f[i]
last = tempList[-1]
if(f[i] == "\""):
closed = True
#tempList[-1] = tempList[-1][:-1]#remove this
elif(f[i] == "(" and closedRoundBracket): #let args exist in round brackets
closedRoundBracket = False
elif(closedRoundBracket == False):
tempList[-1] = last + f[i]
last = tempList[-1]
if(f[i] == ")"):
closedRoundBracket = True
tempList[-1] = tempList[-1][:-1]
elif(not(f[i] in possibleArgs)):
tempList.append(f[i])
last = f[i]
else:
tempList[-1] = last + f[i]
last = tempList[-1]
return(tempList * rep)
def solveArg(arg):
#global argRaw
try:
l = locals()
arg2 = "x="+ str(arg)
exec(arg2, locals())
arg = l["x"]
v.argRaw = arg
except:
pass
return(arg)
def clean(value): #experimental
try:
if(float(value) == int(value)):
return(int(value))
except:
pass
try:
return(float(value))
except:
pass
if(type(value) == tuple):
return(list(value))
return(value)
def runCommand(c):
#global storage
#global pointer
#global argFlag
#global argFlag2
#global argRaw
#global loopIterator
func = c[0]
if(func == " " or func == "\n"):
return
arg = c[1::]
v.argRaw = arg
inLoop = func == "]" and arg != None and arg != "" and (v.loopOrIf == [] or v.loopOrIf[-1])
if("^" in arg):
arg = arg.replace("^","")
v.argFlag = True
else:
v.argFlag = False
if("?" in arg):
arg = arg.replace("?","")
v.argFlag2 = True
else:
v.argFlag2 = False
if("_" in arg):
arg = arg.replace("_","-")
v.argRaw = arg
if("\\" in arg):
arg = arg.replace("\\",str(v.secondArg))
v.argRaw = arg
if("~" in arg):
if(inLoop):
arg = arg.replace("~",str(v.intoLoopArgs[-1][1]))
v.argRaw = v.storage[v.pointer]
else:
try:
arg = arg.replace("~",str(v.storage[v.pointer]))
except:#list...
import ast
arg = arg.replace("~", str(v.storage[v.pointer]))
arg = ast.literal_eval(arg)
#arg = [n.strip() for n in arg]
v.argRaw = v.storage[v.pointer]
#ADD CASE FOR inFunction as well!!!!!!!!!!!!!!!!!!! @todo
if("`" in arg):
if(inLoop):
arg = arg.replace("`",str(v.intoLoopArgs[-1][0]))
v.argRaw = v.topOfStack
else:
arg = arg.replace("`",str(int(v.topOfStack)))
v.argRaw = v.topOfStack
if("@" in arg):
if(inLoop):
arg = arg.replace("@",str(v.intoLoopArgs[-1][2]))
else:
arg = arg.replace("@",str(int(v.pointer)))
if("#" in arg): #NEEDS TO BE REPLACED LAST
if("#" == arg):
arg = str(int(v.loopIterator[-1]))
v.argRaw = arg
else:
import re
#pieces = arg.split("+").split("-").split("*").split("/").split("\"").split("%").split("==")
pieces = re.split("\+|-|\*|/|\"|%|==|\*\*", arg)
import copy
piecesCopy = copy.deepcopy(pieces)
for i in range(len(pieces)):
if("#" in pieces[i]):
coarg = int(pieces[i].replace("#",""))
pieces[i] = v.loopIterator[-(1+coarg)]
arg = arg.replace(str(piecesCopy[i]), str(pieces[i]), 1)
#coarg = int(arg.replace("#",""))
#arg = loopIterator[-(1+coarg)]
#argRaw = arg
#print(arg, type(arg))
arg = solveArg(arg)
if(type(arg) == tuple):
arg = list(arg)
#print("here3", arg)
if(arg != ""): #PARSE ARG AS INT OR FLOAT IF POSSIBLE
try:
v.argRaw = float(v.argRaw)
if("." in arg):
arg = float(arg)
else:
arg = int(float(arg))
except:
pass
if(arg == ""):
arg = None
if("&" in str(arg)):#changes arg to a list
arg = arg.split("&")
for i in range(len(arg)):
try:
if("." in arg[i]):
arg[i] = float(arg[i])
else:
arg[i] = int(float(arg[i]))
except:
pass
#print(arg, type(arg))
functionDict = {
"+":add,
"-":subtract,
"*":multiply,
"/":divide,
"w":helloWorld,
"R":reformat, #arg 000000... where the first digit is type (1=int, 2=string, 3=float) - see below for details about remaining digits
"s":store,
"g":get,
"<":pointerDown,#also used for comparison operator
">":pointerUp,#also used for comparison operator
"P":setPointer,
"p":prnt,
"!":flag,
"c":concat,
"[":startLoop,
"]":endLoop,
"%":modulo,
"$":swap,
"r":secondArgument,
"=":topOfStackEquals,
"v":pointedValueInStorageEquals,
"t":stringFunction,
",":printCharAt,
"a":arrayInitFunctions,
"A":arrayOperations,#array operations (maybe for matrices too)
"m":matrixInitFunctions,
"S":selectFromArray,
"b":concatToPrintBuffer,
"B":printAndResetBuffer,
"i":printInteger,
"q":quitProgram,
"I":storeInput,
"f":executeFunction,
"d":debugIndex,
"n":getInteger,
"e":exponentiate,
"F":executeLocalFunction,
"l":listOperation
}
#exec(functionDict(func) + "(" +str(arg)+")")
(functionDict[func])(arg)
#maybe make a function run inside a VM - call parser again?
#(still partially under construction)
#add a flag which can order a function to run locally - i.e. not affecting main memory
#calling 'f' without an argument ends the current function
def executeFunction(functionIndex):
#global inFunction
#global functions
#global commands
#global skipTo
#global currentCommandIndex
#global endFunctionFlag
#global commandsCopyF
#global functionCommandList
#global currentCommandIndexF
#global currentFunction
#global loopList
#global firstError
v.loopListList.append(copy.deepcopy(v.loopList))
print("here1",v.loopListList)
v.inFunctionList.append(True)
v.inFunction = v.inFunctionList[-1]
#print("function: ", functionIndex)
if(functionIndex == None):
v.endFunctionFlag = True
print("here2",v.loopList)
'''
while(v.currentCommandIndexF[-1] < len(v.functionCommandList[v.currentFunction])):
if(v.functionCommandList[v.currentFunction][v.currentCommandIndexF[-1]][0] == "]"):
del v.loopList[-1]
if(v.functionCommandList[v.currentFunction][v.currentCommandIndexF[-1]][0] == "]"):
v.loopList.append(0)
v.currentCommandIndexF[-1] += 1'''
#currentCommandIndex = skipTo.pop(-1)
#print("skipTo after pop: ", skipTo)
else:
v.currentFunction = functionIndex
v.functionCommandList[v.currentFunction] = getCommandList(v.functions[functionIndex],1)
v.commandsCopyF[v.currentFunction] = getCommandList(v.functions[functionIndex],1)
'''try:
v.functionCommandList[v.currentFunction].remove("\n")
v.commandsCopyF[v.currentFunction].remove("\n")
except:
pass'''
from time import perf_counter as currentTime
start = currentTime()
v.currentCommandIndexF.append(0)
while(v.currentCommandIndexF[-1] < len(v.functionCommandList[v.currentFunction])):
if(v.endFunctionFlag):
v.endFunctionFlag = False
break
v.inFunction = True
try:
runCommand(v.functionCommandList[v.currentFunction][v.currentCommandIndexF[-1]])
except Exception as error:
error_string = str(error)
if(v.firstError):
errorout("Error: " + error_string + " in function " + str(v.currentFunction) + " at function command index " + str(v.currentCommandIndexF[-1]) + " [" + str(v.functionCommandList[v.currentFunction][v.currentCommandIndexF[-1]]) + "]")
v.firstError = False
else:
errorout("Error: " + error_string + " at function command index " + str(v.currentCommandIndexF[-1]) + " [" + str(v.functionCommandList[v.currentFunction][v.currentCommandIndexF[-1]]) + "]")
#v.currentCommandIndexF.pop(-1)
v.currentFunction = functionIndex
raise(Exception("error in function " + str(v.currentFunction)))
v.currentCommandIndexF[-1] += 1
if(currentTime() > start + 5):
printout("Program timed out. Did you forget your exit condition?")
return
v.currentFunction = functionIndex
#print("done function: ", functionIndex)
#print(functionCommandList, currentCommandIndexF)
v.currentCommandIndexF.pop(-1)
#for i in range(len(skipTo)):
# skipTo[i] += len(functionCommandList)
#skipTo.append(currentCommandIndex + len(functionCommandList))
#print("skipTo: ", skipTo)
#for i in range(len(functionCommandList)):
# commands.insert(currentCommandIndex + 1 + i, functionCommandList[i])
#print(commands)
#don't parse a function - insert its operations into queue
del v.inFunctionList[-1]
v.loopList = v.loopListList[-1]
del v.loopListList[-1]
print("here3", v.loopList)
if(len(v.inFunctionList)==0):
v.inFunction = False
else:
v.inFunction = True
def debugIndex(arg):
printout("d" + str(arg) + " has been executed")
def reformat(arg):
fmt = str(arg)
#first digit is type, next is arg to pass to sub-function
#for int, arg is sig digs #except zero case
#for float, arg is digits after decimal (rounded) #except zero case
#for string, arg is no. of characters trimmed from each end
if(len(fmt) == 1):
fmt += "0"
if(fmt[0] == "1"):
mint(int(fmt[1::]))
elif(fmt[0] == "2"):
mstr(int(fmt[1::]))
elif(fmt[0] == "3"):
mfloat(int(fmt[1::]))
elif(fmt[0] == "4"):
if(v.argFlag):
v.topOfStack = format(int(v.topOfStack), "#x")
else:
v.topOfStack = format(int(v.topOfStack), "#x")[2::]
elif(fmt[0] == "5"):
if(v.argFlag):
v.topOfStack = format(int(v.topOfStack), "#010b")
else:
v.topOfStack = format(int(v.topOfStack), "#010b")[2::]
def mint(sigdigs=0):
#global topOfStack
if(sigdigs == 0):
v.topOfStack = int(float(v.topOfStack))
return
else:
from math import log
b = int(log(float(v.topOfStack),10))
v.topOfStack = int(float(v.topOfStack)/10**(b+1-sigdigs)) *10**(b+1-sigdigs)
def mstr(arg=0):
#global topOfStack
if(arg == 0 or arg == None):
v.topOfStack = str(v.topOfStack)
else:
v.topOfStack = v.topOfStack[arg:-(arg)]
def mfloat(sigdigs=0):
#global topOfStack
if(sigdigs == 0):
v.topOfStack = float(v.topOfStack)
else:
v.topOfStack = round(float(v.topOfStack), sigdigs)
def cleanTopOfStack():
#makes any values in the top of the stack into an int if possible without loss of precision
#global topOfStack
if(type(v.topOfStack) == tuple):
v.topOfStack = list(v.topOfStack)
if(type(v.topOfStack) != list):
try:
if(v.topOfStack == int(v.topOfStack)):
v.topOfStack = int(v.topOfStack)
except:
pass
return
for i in range(len(v.topOfStack)):
try:
if(v.topOfStack[i] == int(v.topOfStack[i])):
v.topOfStack[i] = int(v.topOfStack[i])
except:
pass
def helloWorld(arg):#hello, world with variants
if(v.argFlag):#given ^ as arg
printout("Hello world")
elif(v.argFlag2):#given ? as arg
printout("Hello world!")
elif(arg == None):
printout("Hello, World!")
elif(arg == 0):
printout("hello world")
else:
printout("Hello, World!"*(arg+1))
def add(arg):#add arg to stack
#adds 1 to top of stack
#given arg, adds arg to top of stack
#global topOfStack
#global argRaw
#print(arg, type(arg))
if(type(v.topOfStack) == str or type(arg) == str):
v.topOfStack = str(v.topOfStack) + str(arg)
return
if(type(v.topOfStack) == list):
if(arg==None):
v.topOfStack = [elem + 1 for elem in v.topOfStack]
else:
v.topOfStack = [elem + v.argRaw for elem in v.topOfStack]
cleanTopOfStack()
return()
mfloat()
if(arg==None):
v.topOfStack += 1
else:
v.topOfStack += v.argRaw
cleanTopOfStack()
def subtract(arg):#subtract arg from stack
#subtracts 1 from top of stack
#given arg, subtracts arg from top of stack
#global topOfStack
if(type(v.topOfStack) == str or type(arg) == str):
v.topOfStack = v.topOfStack.replace(str(arg), "")
return
if(type(v.topOfStack) == list):
if(arg==None):
v.topOfStack = [elem - 1 for elem in v.topOfStack]
else:
v.topOfStack = [elem - v.argRaw for elem in v.topOfStack]
cleanTopOfStack()
return()
mfloat()
if(arg==None):
v.topOfStack -= 1
else:
v.topOfStack -= v.argRaw
cleanTopOfStack()
def divide(arg):#divide stack/arg
#divides the top of stack by 2
#given 0 as arg, divides top of stack by 10
#given other arg, divides top of stack by arg
#global topOfStack
if(type(v.topOfStack) == list):
if(arg==None):
v.topOfStack = [elem / 2 for elem in v.topOfStack]
else:
v.topOfStack = [elem / v.argRaw for elem in v.topOfStack]
cleanTopOfStack()
return()
mfloat()
if(arg==None):
v.topOfStack /= 2
#elif(argRaw == 0):
# topOfStack /= 10
else:
v.topOfStack /= v.argRaw
if(v.topOfStack == int(v.topOfStack)):
v.topOfStack = int(v.topOfStack)
def multiply(arg):#stack*=arg
#multiplies the top of stack by 2
#given 0 as arg, multiplies top of stack by 10
#given other arg, multiplies top of stack by arg
#global topOfStack
#mfloat()
#print(arg)
if(type(v.topOfStack) == list):
if(type(arg) == list):
temp = []
for i in range(len(v.topOfStack)):
temp.append(v.topOfStack[i] * arg[i])
v.topOfStack = temp
return
if(arg==None):
v.topOfStack = [elem * 2 for elem in v.topOfStack]
else:
v.topOfStack = [elem * v.argRaw for elem in v.topOfStack]
cleanTopOfStack()
return()
if(arg==None):
v.topOfStack *= 2
#elif(argRaw == 0):
# topOfStack *= 10
else:
v.topOfStack *= v.argRaw
if(type(v.topOfStack) != str and v.topOfStack == int(v.topOfStack)):
v.topOfStack = int(v.topOfStack)
def store(arg):#if the arg is None, it should instead use the current pointer
#stores the top of the stack at the current pointer
#given an arg, stores the top of the stack at arg in storage
#global storage
#global topOfStack
if(type(arg) == str):
v.storage[v.pointer] = arg
elif(arg != None):
v.storage[arg] = v.topOfStack
else:
v.storage[v.pointer] = v.topOfStack
def get(arg):
#sets the top of the stack to the value at the pointer
#given an arg, sets the top of the stack to the value at arg
#global storage
#global topOfStack
if(arg != None):
v.topOfStack = v.storage[arg]
else:
v.topOfStack = v.storage[v.pointer]
def pointerUp(arg):
#moves the pointer up
#given an arg, moves the pointer up arg places
#global pointer
if(arg == None):
if(v.pointer != len(v.storage)-1):
v.pointer += 1