开发者

How does an interpreter switch scope?

I'm asking this because I'm relatively new to interpreter development and I wanted to know some basic concepts before reinventing the wheel.

I thought of the values of all variables stored in an array which makes开发者_如何学C the current scope, upon entering a function the array is swapped and the original array put on some sort of stack. When leaving the function the top element of the "scope stack" is popped of and used again.

  • Is this basically right?
  • Isn't swapping arrays (which means moving around a lot of data) not very slow and therefore not used by modern interpreters?


Why swap the array? Just look at the top array on your stack. Furthermore, in most languages you don’t have to copy the array when you want to swap it, you can just swap references or pointers.

This is also what an interpreter might do. An alternative is having a special data structure for the current scope which holds a reference to its parent frame explicitly.


Python uses the C stack to keep track of its scope. Everytime a new scope is entered a new function call is made so that the scope's data is always held in the local variables on the stack.

For some other interpreters, everything is kept on the stack something like your suggestion. However, the interpreter acts on the top of the stack in-place. There is no need to copy things back and forth since there is only one copy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜