我正在创建一种编程语言。对于这种语言,我正在创建一个将其编译成 Python 的程序。我不需要词法分析器,因为大部分语法都可以用正则表达式转换成 Python。
这是我目前所拥有的:
import re
infile = input()
output = open(infile + ".py","w")
input = open(infile + ".hlx")
# I'm aware the .hlx extension is already taken, but it doesn't really matter.
for line in input:
output.write(re.sub(r'function (\S+) (\S+) =', r'def \1(\2):', line))
for line in input:
output.write(re.sub(r'print(.+)', r'print(\1)', line))
for line in input:
output.write(re.sub(r'call (\S+) (\S+)', r'\1(\2)', line))
# More regexes go here, eventually.
input.close()
output.close()
我必须将每个正则表达式放在一个单独的 for 语句中,因为如果我将它们放在一起,它会替换每一行 3 次。
这里的问题是它只执行一个正则表达式,也就是第一个。顺序在这里并不重要,但我仍然需要程序来执行所有的正则表达式。我该怎么做?
顺便说一句,这是我想用我的语言替换的代码:
function hello input =
print "Hello, ", input, "!"
hello "world"
下面是我想用 Python 替换它的代码:
def hello(input):
print("Hello, " + input + "!")
hello("world")
请您参考如下方法:
在一个循环中一个接一个地执行所有替换。我还建议将正则表达式及其替换放在单独的数据结构中,这将使进一步的扩展更容易:
conversions = (
(r'function (\S+) (\S+) =', r'def \1(\2):'),
(r'print(.+)', r'print(\1)' ),
(r'call (\S+) (\S+)', r'\1(\2)' ),
)
for line in input:
for (pattern, sub) in conversions:
line = re.sub(pattern, sub, line)
output.write(line)
