Add nested-function support in a language the based on a stack-machine

231 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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.