所以我正在努力创建一种简单的、可编译为 C 的语言,它的语法类似于 Python。这是一些示例源代码:
# All comments start with pound signs
# Integer declaration
speed = 4
motor = 69.5
text = "hey + guys!"
junk = 5 +4
# Move function
def move():
speed = speed + 1
print speed
# Main function (program entry)
def main():
localvar = 43.2
move()
if true:
print localvar
与 Python 一样,该语言通过缩进策略强调可读性。它还有一个非常松散的类型声明系统。类型由上下文决定。
object = 5 // Creates an integer
object_two = "stuff" // Creates a string
object_three = 5.23 // Creates a float
我上面的示例源代码在内部表示如下:
[
[
"GLOBAL",
[
"speed = 4",
"motor = 69.5",
"text = \"hey + guys!\"",
"junk = 5 +4"
],
[
"SCOPE",
[
"speed",
"motor",
"text",
"junk"
],
[
"INT",
"FLOAT",
"STRING",
"INT"
],
[
0,
1,
2,
3
]
]
],
[
"def move():",
[
" speed = speed + 1",
" print speed"
],
[
"SCOPE",
[
"speed",
"motor",
"text",
"junk"
],
[
"GLOBAL",
"GLOBAL",
"GLOBAL",
"GLOBAL"
],
[
0,
1,
2,
3
]
]
],
[
"def main():",
[
" localvar = 43.2",
" move()",
" if true:",
" print localvar"
],
[
"SCOPE",
[
"speed",
"motor",
"text",
"junk",
"localvar"
],
[
"GLOBAL",
"GLOBAL",
"GLOBAL",
"GLOBAL",
"FLOAT"
],
[
0,
1,
2,
3,
0
]
]
]
]
每个函数都与各自的局部变量及其类型(也是它们在函数中声明的行的索引)一起打包到此表示中。
我正在尝试将此中间表示转换为实际的 C 代码(实际上它是 NXC 代码,因此它与 C 略有不同)。
我的问题是如何理解变量类型(特别是在函数参数中声明的变量)。我可以做到这一点的唯一方法是根据调用函数的上下文进行猜测。
更不用说,我正在以线性方式创建中间表示。如果一个函数被定义但直到稍后才被调用,会发生什么?在获得所有必要的类型信息之前,我是否需要多次运行来修改这个中间表示?