我正在使用 python 来实现另一种名为 'foo' 的编程语言。foo 的所有代码都会被翻译成 python,并且也会在同一个 python 解释器中运行,所以它会 JIT 翻译成 python。
下面是一小段 foo 的代码:
function bar(arg1, arg2) {
while (arg1 > arg2) {
arg2 += 5;
}
return arg2 - arg1;
}
这将转化为:
def _bar(arg1, arg2):
while arg1 > arg2:
arg2 += 5
watchdog.switch()
watchdog.switch()
return arg2 - arg1
“看门狗”是一个greenlet(生成的代码也在greenlet上下文中运行),它将监控/限制资源使用,因为该语言将运行不受信任的代码。
从示例中可以看出,在生成 python 代码之前,将对解析树进行小幅更改,以便添加看门狗开关并对函数标识符进行小幅更改。
为了满足所有要求,我还必须在语言中添加回溯/调试功能,这样当 python 运行时抛出异常时,用户将看到的是 foo 的代码回溯(而不是显示生成的 python 代码回溯)。
假设用户创建了一个名为“program.foo”的文件,其内容如下:
1 function bar() {
2 throw Exception('Some exception message');
3 }
4
5 function foo() {
6 output('invoking function bar');
7 bar();
8 }
9
10 foo();
这将转化为:
def _bar():
watchdog.switch()
raise Exception('Some exception message')
def _foo():
print 'invoking function bar'
watchdog.switch()
_bar()
watchdog.switch()
_foo()
然后,“program.foo”的输出应该是这样的:
invoking function bar
Traceback (most recent call last):
File "program.foo", line 10
foo();
File "program.foo", line 7, inside function 'foo'
bar();
File "program.foo", line 2, inside function 'bar'
throw Exception('Some exception message');
Exception: Some exception message
有没有简单的方法可以做到这一点?我更喜欢不涉及检测 python 字节码的解决方案,因为它是解释器实现的内部,但如果没有别的,那么检测字节码也可以做到。