Static links - how to determine the number of steps to reach an outer scope local?

不想你离开。 提交于 2019-12-11 13:56:54

问题


I've been reading about using static (aka access) links to implement nested procedures. I have no trouble understanding the concept except how to determine how many "hops" are needed to reach the stack frame of the function that contains the local we want to access.

Many sources - among them, this PDF handout (page 4) - list two cases:

Suppose f calls g. Let nf = nesting level of f and ng = nesting level of g. We now have two cases:

1) nf < ng --- the callee is nested more deeply than the caller. g is thus declared inside of f, and so the static link should point to the caller's stack frame.

2) nf >= ng --- the nest levels are equal, or the nested function is calling the containing function. In that case, follow nf - ng + 1 static links to determine the stack frame to be pushed.

While I'm okay with case 1, I don't really understand how the second case would work. Consider the following pseudocode:

procedure A()
{
    local u;
    procedure B()
    {
        u = 0;
    }

    procedure C()
    {
        B();
    }

    C();
}

When we call A, a stack frame is created for it. A then calls C, which proceeds to call B. B must resolve the reference to the non-local variable u; according with the steps outlined above, it should traverse 1 - 1 + 1 static links on the stack to get to the appropriate stack frame; however, in doing so, it will end up in C's stack frame instead. The issue gets even more complex when recursion is considered - the static nest level does not change, however there will be multiple stack frames/activation records on the stack for the recursive function.

I think my problem comes from misunderstanding the concept in one way or another; I would appreciate it if someone pointed out the flaws in my reasoning.

来源:https://stackoverflow.com/questions/37102865/static-links-how-to-determine-the-number-of-steps-to-reach-an-outer-scope-loca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!