NCL 506: Stack Frames and Recursion

So far, every subroutine we've written has called other subroutines.

There's nothing stopping a subroutine from calling itself.

Consider factorial.

The factorial of 4 is:

4 × 3 × 2 × 1 = 24

We can also describe it like this:

factorial(4)
= 4 × factorial(3)

factorial(3)
= 3 × factorial(2)

factorial(2)
= 2 × factorial(1)

factorial(1)
= 1

Each calculation asks for a smaller version of the same calculation.

Eventually, we reach 1, where we already know the answer.

This suggests a subroutine with an unusual property:

:factorial can call :factorial.

Calling Yourself

Suppose :factorial takes one integer and returns one integer.

Its interface could look like this:

Takes Type
value Integer
Returns Type
result Integer

For values greater than 1, the calculation is:

factorial(n) = n × factorial(n - 1)

For 1, the result is simply:

factorial(1) = 1

A subroutine that calls itself is recursive.

Let's try writing one.

:factorial
POP $000

BLE :base $000 1

SUB $001 $000 1
PUSH $001
CALL :factorial
POP $001

MUL $002 $000 $001
PUSH $002
RET

:base
PUSH 1
RET

It certainly looks plausible.

If $000 contains 4, we calculate 3 and call :factorial again.

That invocation calculates 2 and calls :factorial again.

Then 1.

But there's a problem.

One n Per Call

Let's follow $000.

Invocation $000
factorial(4) 4
factorial(3) 3
factorial(2) 2
factorial(1) 1

Scratch is shared.

The recursive call doesn't get a new $000. It uses exactly the same $000 as the invocation that called it.

By the time the deepest call returns, the original 4 is gone.

So are the 3 and 2.

But each invocation still needs its own value to finish its multiplication:

factorial(4) still needs 4
factorial(3) still needs 3
factorial(2) still needs 2

There isn't one n.

There is one n for each invocation.

Putting State Aside

We've already learned how to protect a value across a call.

Before calling another subroutine, we can push a value we still need:

PUSH $000

After the call returns, we can recover it:

POP $000

Recursion uses exactly the same idea.

Suppose the current invocation is calculating factorial(4).

Before asking for factorial(3), it saves its 4.

The next invocation saves its 3.

Then the next saves its 2.

Current invocation Value stack, top first
factorial(4) 4
factorial(3) 3, 4
factorial(2) 2, 3, 4

Each invocation has put aside the state it will need when the deeper call eventually returns.

That state belongs to one particular invocation of the subroutine.

We call it a stack frame.

A stack frame is the value-stack state belonging to one invocation of a subroutine.

A frame might contain one value.

It might contain several.

Its exact contents depend on what that invocation needs to remember.

Just like the structures we built in the 400-level, there is no special FRAME instruction.

A stack frame is another agreement about what some memory means.

Two Different Stacks

We've now encountered two stacks involved in the same call.

They do different jobs.

Structure Holds
Internal call stack Return addresses
Value stack Arguments, results, and stack frames

When we execute:

CALL :factorial

the CPU automatically remembers the return address on its internal call stack.

Our program cannot directly access that stack.

The values we save ourselves with PUSH go onto the value stack.

So a recursive invocation can have two kinds of state at once:

The call stack remembers where an invocation returns.

The stack frame remembers what that invocation was doing.

A Frame for Factorial

Let's fix our recursive routine.

When an invocation knows it will need its current value later, it saves that value before making the recursive call:

PUSH $000

Then it prepares the smaller problem:

SUB $001 $000 1
PUSH $001
CALL :factorial
POP $001

When the recursive call returns, $001 contains its result.

Now this invocation can recover its own value:

POP $000

and finish its calculation:

MUL $002 $000 $001

For factorial(4), the calls descend like this:

factorial(4)
    factorial(3)
        factorial(2)
            factorial(1)

While they descend, the saved state accumulates:

Current invocation Value stack, top first
factorial(4) 4
factorial(3) 3, 4
factorial(2) 2, 3, 4

The values in Scratch keep changing.

That's fine.

The values that must survive are waiting on the value stack.

The Base Case

A recursive subroutine needs some path that does not call itself again.

For factorial, that's:

factorial(1) = 1

So our routine checks for it before making another call:

BLE :base $000 1

The :base path can return immediately:

:base
PUSH 1
RET

This is the base case.

Without a base case, every invocation would make another invocation:

call
    call
        call
            call
                call
                    ...

Nothing would ever begin returning.

A recursive problem needs some point where it becomes simple enough to answer directly.

Coming Back

Once factorial(1) returns 1, the calls begin unwinding.

The invocation calculating factorial(2) recovers its saved 2:

2 × 1 = 2

It returns 2.

The previous invocation recovers its 3:

3 × 2 = 6

It returns 6.

Then:

4 × 6 = 24

The recursion has unwound all the way back to the original caller.

factorial(1) → 1
factorial(2) → 2
factorial(3) → 6
factorial(4) → 24

The value stack works particularly well here because it is LIFO.

The most recent invocation is the first one that needs to recover its state.

Then the invocation before it.

Then the one before that.

The frames disappear in exactly the opposite order from which they were created.

Putting It Together

Here's the complete recursive factorial:

:factorial
POP $000

BLE :base $000 1

-- Save this invocation's value.
PUSH $000

-- Ask for factorial(value - 1).
SUB $001 $000 1
PUSH $001
CALL :factorial
POP $001

-- Recover this invocation's value.
POP $000

-- Finish this invocation's calculation.
MUL $002 $000 $001
PUSH $002

FREE $000
FREE $001
FREE $002
RET

:base
PUSH 1

FREE $000
FREE $001
FREE $002
RET

Nothing special happened to Scratch when we called ourselves.

Nothing special happened to the value stack either.

We used the same CALL, RET, PUSH, and POP we've already learned.

The important change was how we organized the temporary state.

Each invocation saved what it needed before allowing another invocation to use the same workspace.

Keep an eye on call depth

NCL's internal call stack can hold 32 pending return addresses.

For recursion whose depth might depend on input, it can be useful to keep track of the current call depth in software and refuse to make another CALL when no more return slots are available.

One simple convention is to pass the current depth alongside the recursive arguments and increment it before each recursive call.

A routine executing at depth 32 can still finish its own work, but it cannot safely make another CALL.

This is separate from the recursive base case. The base case says when the algorithm is finished; a depth limit prevents the implementation from exceeding the machine's available call depth.

Two finite resources

Recursive calls can consume two different finite resources.

Every pending CALL occupies one entry in the CPU's internal call stack.

Values saved in stack frames occupy space on the value stack.

Limiting call depth protects the first. It does not guarantee that enough value-stack space remains for every frame.

Try It

Here's another recursive definition:

power2(0) = 1
power2(n) = 2 × power2(n - 1)

So:

power2(4)
= 2 × power2(3)
= 2 × 2 × power2(2)
= 2 × 2 × 2 × power2(1)
= 2 × 2 × 2 × 2 × power2(0)
= 16

Write a :power2 subroutine with this interface:

Takes Type
exponent Integer
Returns Type
result Integer

Your subroutine should call itself to calculate the smaller power.

Think about four things:

  1. What is the base case?
  2. What value does each invocation need after its recursive call returns?
  3. What belongs in that invocation's stack frame?
  4. In what order will those frames be recovered?

Test it with:

PUSH 4
CALL :power2
POP $000

The result should be:

$000 = 16
Where does recursion stop?

Start with the definition:

power2(0) = 1

There is no smaller problem to solve when the exponent reaches 0.

Still stuck?

Your subroutine needs a branch that reaches a path which pushes 1 and returns without making another recursive call.

What needs to survive?

For an exponent greater than 0, the calculation is:

2 × power2(exponent - 1)

Ask what the current invocation still needs after power2(exponent - 1) returns.

Still stuck?

This version doesn't actually need the original exponent after the recursive call.

The recursive result is enough:

result × 2

Not every recursive routine needs to save local state across its recursive call.

Build the smaller call

Subtract 1 from the exponent and pass that value to another invocation of :power2.

When it returns, double the result.

Still stuck?

The middle of the routine can follow this shape:

SUB $001 $000 1
PUSH $001
CALL :power2
POP $001

MUL $001 $001 2
Show me one solution
:power2
POP $000

BLE :base $000 0

SUB $001 $000 1
PUSH $001
CALL :power2
POP $001

MUL $001 $001 2
PUSH $001

FREE $000
FREE $001
RET

:base
PUSH 1

FREE $000
FREE $001
RET

Notice something interesting about this solution.

:power2 is recursive, but it doesn't need to preserve its original exponent across the recursive call.

Once it has calculated exponent - 1, the original value is no longer needed.

The recursive result itself is enough to finish the calculation.

Stack frames contain the per-invocation state a routine needs.

They don't need to contain values merely because those values existed earlier in the call.


We've seen how a subroutine can call itself, how each invocation can keep its own temporary state in a stack frame, and how recursive calls eventually unwind through a base case.

In the next lesson, NCL 507: Handlers, we'll look at a much less mechanical question: how much work should one subroutine be responsible for?