我正在使用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
.

'看门狗'是一个绿色的(生成的代码也在绿色上下文中运行),它将监视/限制资源使用情况,因为语言将运行不受信任的代码。

在该示例中可以看出,在生成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
.

有没有简单的方法?我更喜欢一个不涉及仪器的解决方案,因为它是Interpreter实现的内部,但如果没有别的,那么仪器字节码也会这样做。

有帮助吗?

解决方案

You could decorate each generated Python function with a decorator which record the context (filename, function, line number, etc.) to a global stack. Then you could derive your own Exception class and catch it at the top level of the interpreter. Finally, you print out what you like, using information from the global debug stack.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top