-
Notifications
You must be signed in to change notification settings - Fork 0
/
tforth.py
389 lines (327 loc) · 11.1 KB
/
tforth.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
import sys
_code =""
if len(sys.argv) == 1:
print("expected tforth.py [filename]")
exit(1)
code = open(sys.argv[1],'r').read().replace("\\n","\n")
"""
: CR 10 EMIT ;
: IF INVERT BC ;
: THEN LBL ;
: ELSE LBL BC ;
: BEGIN LBL ;
: UNTIL BC ;
VARIABLE i
VARIABLE end
: DO ! ! LBL ;
: LOOP
DUP DUP ( duplicates index VARIABLE )
@ 1 + SWAP ! ( Increment index )
@ SWAP @ < ( Compare )
BC ; ( Branch )
90 end 0 i
DO
i @ . CR
end i
LOOP
VARIABLE vtest
0 vtest !
(
BEGIN
vtest @ 1 + vtest !
vtest @ . CR
vtest @ 10 <
UNTIL
)
"""
stk = [0 for i in range(0,16000)]
tokens = []
buffer = ""
i=0
while i < len(code):
if(code[i] == "\n" or
code[i] == "\t" or
code[i] == "\r" or
code[i] == ' '):
if(buffer != ""):
tokens.append(buffer.upper())
buffer = ""
i+=1
continue;
buffer += code[i]
if(code[i] == '"'):
tokens.append(buffer)
buffer=""
i+=1
while(code[i] == ' '):
i+=1
while(code[i] != '"'):
buffer += code[i]
i+=1
i+=1
tokens.append(buffer)
buffer=""
i+=1
for i in range(tokens.count("")): #remove white space
tokens.remove("")
def printn(s):
print(s,end = "")
pc = 0
label_jmp_flag = 0
varible_pointer_counter = 10000
string_pointer_counter = 8000
user_def_word = {}
primative_words = {}
primative_words["."] = lambda : printn(str(stk.pop()))
primative_words["EMIT"] = lambda : printn(chr(stk.pop()))
primative_words["DUP"] = lambda : stk.append(stk[-1]);
primative_words["DROP"] = lambda : stk.pop();
def ADD(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 + op1)
def SUB(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 - op1)
def MUL(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 * op1)
def DIV(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 / op1)
def LESS(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 < op1)
def GREATER(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 > op1)
def EQUAL(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 == op1)
def AND(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 & op1)
def OR(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 | op1)
def XOR(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op2 ^ op1)
def INVERT(): global stk; op1 = stk.pop();stk.append( not op1)
def DEREF(): global stk; op1 = stk.pop();stk.append(stk[op1])
def WRITEMEM(): global stk; op1 = stk.pop(); stk[op1]= stk.pop()
def SWAP(): global stk; op1 = stk.pop();op2 = stk.pop();stk.append( op1);stk.append( op2)
def IMPORT():
global tokens,pc
code = open(tokens[pc],'r').read().upper()
tokens_external = []
buffer = ""
i=0
while i < len(code):
if(code[i] == "\n" or
code[i] == "\t" or
code[i] == "\r" or
code[i] == ' '):
if(buffer != ""):
tokens_external.append(buffer.upper())
buffer = ""
i+=1
continue;
buffer += code[i]
if(code[i] == '"'):
tokens_external.append(buffer)
buffer=""
i+=1
while(code[i] == ' '):
i+=1
while(code[i] != '"'):
buffer += code[i]
i+=1
i+=1
tokens_external.append(buffer)
buffer=""
i+=1
pc-=1
tokens.pop(pc)
tokens.pop(pc)
for i in range(0,len(tokens_external)):
tokens.insert(pc+i,tokens_external[i])
def STRING():
global string_pointer_counter, tokens,pc, stk
i = 0
stk.append(string_pointer_counter)
for i in range(0,len(tokens[pc])):
stk[string_pointer_counter] = ord(tokens[pc][i])
string_pointer_counter+=1
i+=1
stk.append(len(tokens[pc])-2)
string_pointer_counter+=1
pc+=1
def FLPJF(): # flips jump flag forcing program to jump wherever you want
global label_jmp_flag
label_jmp_flag ^= 1
def LBL(): global label_jmp_flag; label_jmp_flag = 1
primative_words["IMPORT"] = IMPORT
primative_words["+"] = ADD
primative_words["-"] = SUB
primative_words["*"] = MUL
primative_words["/"] = DIV
primative_words["<"] = LESS
primative_words[">"] = GREATER
primative_words["="] = EQUAL
primative_words["AND"] = AND
primative_words["OR"] = OR
primative_words["LBL"] = LBL
primative_words["INVERT"] = INVERT
primative_words["@"] = DEREF
primative_words["!"] = WRITEMEM
primative_words["SWAP"] = SWAP
primative_words["S\""] = STRING
primative_words["XOR"] = XOR
primative_words["FLPJF"] = FLPJF
primative_words["STOP"] = lambda : exit(-1)
primative_words["SBLK"] = lambda : 0
primative_words["EBLK"] = lambda : 0
def RKBLK(): # returns to SBLK
global pc,tokens
flag_ = 0
while(tokens[pc] != "SBLK" or flag_ != 0):
if(tokens[pc] in user_def_word and
user_def_word[tokens[pc]]["type"] == "mf" and
(not (tokens[pc] in user_def_word[tokens[pc]]["exp"])) ): expand_mf() ; pc+=1
if(tokens[pc] == "EBLK"): flag_ +=1
if(tokens[pc] == "SBLK"): flag_ -=1
if(tokens[pc] == "SBLK" and flag_ == 0): break
pc-=1
def SKBLK(): # skips block by Jumping to EBLK
global pc,tokens
flag_ = 0
while(tokens[pc-1] != "EBLK" or flag_ != 0):
if(tokens[pc] in user_def_word and
user_def_word[tokens[pc]]["type"] == "mf" and
(not (tokens[pc] in user_def_word[tokens[pc]]["exp"])) ):expand_mf() ; pc-=1;
if(tokens[pc] == "EBLK"): flag_ -=1
if(tokens[pc] == "SBLK"): flag_ +=1
pc+=1
def RKBLKC(): # returns to SBLK if condition
global pc,tokens,label_jmp_flag
if(stk.pop()):
RKBLK()
def SKBLKC(): # skips block by Jumping to EBLK
global pc,tokens,label_jmp_flag
if(stk.pop()):
SKBLK()
def SRKBLK(): # returns to SBLK
global pc,tokens
flag_ = 0
while(tokens[pc-1] != "SBLK" or flag_ != 0):
if(tokens[pc] in user_def_word and
user_def_word[tokens[pc]]["type"] == "mf" and
(not (tokens[pc] in user_def_word[tokens[pc]]["exp"])) ): expand_mf() ; pc+=1
if(tokens[pc] == "EBLK" ): flag_ +=1
if(tokens[pc] == "SBLK"and flag_ != 0): flag_ -=1
if(tokens[pc] == "SBLK" and flag_ == 0): break
pc-=1
#print(tokens[pc],flag_)
#print(tokens[pc],flag_)
def SSKBLK(): # skips block by Jumping to EBLK
global pc,tokens
flag_ = 0
while(tokens[pc] != "EBLK"or flag_ != 0):
if(tokens[pc] in user_def_word and
user_def_word[tokens[pc]]["type"] == "mf" and
(not (tokens[pc] in user_def_word[tokens[pc]]["exp"])) ): expand_mf() ; pc-=1;
if(tokens[pc] == "EBLK"and flag_ != 0): flag_ -=1
if(tokens[pc] == "SBLK" ): flag_ +=1
pc+=1
#print(tokens[pc])
def SRKBLKC(): # returns to SBLK if condition
global pc,tokens,label_jmp_flag
if(stk.pop()):
SRKBLK()
def SSKBLKC(): # skips block by Jumping to EBLK
global pc,tokens,label_jmp_flag
if(stk.pop()):
SSKBLK()
primative_words["RKBLK"] = RKBLK
primative_words["SKBLK"] = SKBLK
primative_words["RKBLKC"] = RKBLKC
primative_words["SKBLKC"] = SKBLKC
primative_words["SRKBLK"] = SRKBLK
primative_words["SSKBLK"] = SSKBLK
primative_words["SRKBLKC"] = SRKBLKC
primative_words["SSKBLKC"] = SSKBLKC
def B():
global pc,tokens,label_jmp_flag
if(label_jmp_flag == 1):
pc-=1
while(tokens[pc] != "LBL"):
if(tokens[pc] in user_def_word and
user_def_word[tokens[pc]]["type"] == "mf" and
(not (tokens[pc] in user_def_word[tokens[pc]]["exp"])) ):
expand_mf()
pc+=1
pc-=1
pc+=1
else:
pc+=1
while(tokens[pc] != "LBL"):
if(tokens[pc] in user_def_word and
user_def_word[tokens[pc]]["type"] == "mf" and
(not (tokens[pc] in user_def_word[tokens[pc]]["exp"])) ):
expand_mf()
pc-=1
pc+=1
pc+=1
primative_words["B"] = B
def BC():
global pc,tokens,label_jmp_flag
if(stk.pop()):
B()
else:
label_jmp_flag = 0
primative_words["BC"] = BC
def get_tok():
global pc
tok = tokens[pc]
pc+=1
return tok
def expand_mf():
global tokens,pc
curtok = tokens[pc]
tokens.pop(pc)
for i in range(0,len(user_def_word[curtok]["exp"])):
tokens.insert(pc+i,user_def_word[curtok]["exp"][i])
#eval mode
def eval_forth():
global pc,stk,primative_words,user_def_word,varible_pointer_counter,_code
while pc < len(tokens):
curtok = get_tok()
if curtok == "RENAME": # gives new name to primatives keeps the old one but that can be over written by defining a userword
primative_words[tokens[pc+1]] = primative_words[tokens[pc]]
pc+=2
elif curtok in user_def_word:
if(user_def_word[curtok]["type"] == "mf"): # obsolete macro expander
pc-=1 # get to name of mf
expand_mf()
elif user_def_word[curtok]["type"] == "var":
stk.append(user_def_word[curtok]["loc"])
elif user_def_word[curtok]["type"] == "compile_word":
_code += user_def_word[curtok]["str"]
elif curtok.isdigit():
stk.append(int(curtok))
elif curtok == ":":
name = tokens[pc]
pc+=1 # skip word name
user_def_word[name] = {"type": "mf", "exp":[]}
while (tokens[pc] != ';'):
user_def_word[name]["exp"].append(tokens[pc])
pc+=1
pc+=1 # skip ;
elif curtok == "VARIABLE":
name = tokens[pc]
pc+=1 # skip word name
user_def_word[name] = {"type": "var", "loc":varible_pointer_counter}
varible_pointer_counter+=1
elif curtok in primative_words:
primative_words[curtok]()
elif curtok == "C:":
name = tokens[pc]
pc+=2 # skip word name and "
user_def_word[name] = {"type": "compile_word", "str":tokens[pc]}
pc+=1 # skip ;
elif curtok == ".C":
_code+=str(stk.pop())
elif curtok == '(':
while(tokens[pc] != ')'):
pc+=1
pc+=1
elif curtok in [';','(',')']: # do nothing
1+1
else:
print(f"User word has not been defined yet: {curtok}")
exit(-1)
eval_forth()
print(_code)
#print()
#print(user_def_word)
#print(stk)