Kajo Lab 101

Forth VM 101.

One Forth word calls another. Follow what the machine does with the numbers and how it remembers where to resume.

Enlarge Kajo Lab paused after DUP, with two sevens on the data stack and address 38 on the return stack.
After DUP, the data stack holds [7 7]. The return stack still holds [38], the address where the caller will resume.

What each stack remembers.

Kajo’s Forth virtual machine (VM) is the software that runs Forth instructions. A stack works like a pile. The last item placed on it is the first one taken off. In Lab, the top of each stack is on the right.

Data stack

Holds the numbers a word works with and the results it leaves behind. The word twice takes 7 and leaves 14.

Return stack

For this call, holds the instruction address where the caller should continue after twice finishes.

Follow the call and return.

Lab starts at on-sample. It pushes 7, calls twice, then adds 1 after that word returns.

: twice DUP + ;
: on-sample 7 twice 1 + ;
Both stacks start empty. The table shows their contents after each instruction.
After this instructionData stackReturn stack
Push 7[7]Empty
Call twice[7][38]
Copy the top with DUP[7 7][38]
Run + inside twice[14][38]
Return from twice[14]Empty
Push 1[14 1]Empty
Run + inside on-sample[15]Empty
Finish on-sample[15]Empty
Why does 38 disappear on return?

When twice returns, the VM takes 38 off the return stack and uses it to set the program counter (PC). In this trace, that address points to the instruction that pushes 1. The 14 on the data stack is still there for the caller to use. The number 38 is an address for this trace and can change with the source or Lab build.

Read both stacks in Kajo Lab.

In Kajo Lab on Windows, use a saved recording to give Lab an observation to inspect. The draft uses its own value of 7. You can run it with the Pico unplugged.

  1. In Lab, choose Open recording or session… and open the downloaded Night Light recording.
  2. In Program, choose Forth and replace Experimental Forth with the two lines above.
  3. Set the observation number to 1, choose Inspect observation and open Stacks.
  4. Use Next frame to stop at the call, the addition inside twice and the return. Continue through the end of on-sample until Lab shows This callback: result 15. The saved observation still shows Recorded callback: result 1.

Try the same call with 9.

Change 7 to 9 in on-sample. Predict what the VM will do before choosing Inspect observation again. You can also work through the questions entirely here.

What is on the data stack when twice returns?

twice leaves [18]. Back in the caller, 1 + changes it to [19]. The callback finishes with 19.

How many addresses does the return stack hold?

It holds one address just after the call and is empty just after the return. The choice of 7 or 9 changes the data, while the machine still has one call to return from.

Study references.