0

Suppose I have a simple C-like programming language:

int foo() {
    int x = 10;
    int bar(y int) {
        return y * 2
    }
    return bar() + x
}

Like you can see, it supports nested functions.
I already implemented the lexing-parsing phases, and now I'm working on the code generation and the stack-machine. most of the operations, and the simple flow-control already implemented but I need some help/ideas how to solve the nested-function task.

The stack-machine has two registers, accumulator, and a temporary register.
Each frame contains: [arguments, local variables, return address, caller frame and stack pointer, temporaries and data operations], and I'm using the same stack for the call-frames and for the operations evaluation. Maybe I should split it into two stacks, one for the call frames, and the second for the operation evaluations.

I read about two ways to implement the nested-function. one, using an activation-link (also called static-link), and display. Is there any better idea to handle this?
If I'll choose one of these idea, is it compile time calculation or do I need to store something in runtime? if it's a runtime thing, what's the time complexity for it? is it O(1) operation, or something like O(k) where k is the depth of the function.

mux
  • 455
  • 5
  • 10
  • The crucial question is whether the nested function can access local variables from the parent function. If not the nested function is like any other function except that it can only be called from inside the parent function and that can be completely resolved prior to code generation. – Johan Feb 12 '18 at 22:01
  • Yes. it should behave like Python for example. – mux Feb 12 '18 at 22:05

1 Answers1

0

a static link requires O(k) time to access an intermediate variable, while a display requires O(k) time to copy it on every frame but always does the variable access in O(2) time. in practice static links are actually slightly faster & work better w/ closures than a display.