我正在尝试制作自己的基本编程语言。我的smrlang.py
文件
from sys import *
tokens = []
def open_file(filename):
data = open(filename, "r").read()
return data
def smr(filecontents):
tok = ""
state = 0
string = ""
filecontents = list(filecontents)
for char in filecontents:
tok += char
if tok == " ":
if state == 0:
tok = ""
else:
tok = " "
elif tok == "PRINT":
tokens.append("PRINT")
tok = ""
elif tok == "\"":
if state == 0:
state = 1
elif state == 1:
print("STRING")
string = ""
state = 0
elif state == 1:
string += tok
print(tokens)
def run():
data = open_file(argv[1])
smr(data)
run()
我在one.smr
文件中有这个:
PRINT "HELLO WORLD"
输出应该类似于PRINT STRING
,但是当我使用命令python3 smrlang.py one.smr
时,输出只是PRINT
。我正在使用Python 3
答案 0 :(得分:0)
调试它的头部,我发现了问题:
elif state == 1:
string += tok
您不在此处重置令牌。它将是aababcabcd
而不是abcd
,并且识别\
将无效(因为它将是aababcabcd\
)。
这也会导致令牌只是一切,而且永远不会打印。
尝试将其更改为:
elif state == 1:
string += tok
tok = ""
修复后的输出:
> py -3 temp.py temp.txt
STRING
['PRINT']