Notes on Chapter 8 - Week 2 of Nand2Tetris Part 2

Unit 2.4: Function Call and Return: Implementation Preview

  • We create state when we run a function
  • We have to save the state and return to it when calling a new function
  • When the function returns, we recycle the state
  • The Calling pattern is LIFO, Last In First Out
  • The frame is the return address and the memory segments of the caller (LCL, ARG, THIS, THAT)
  • 1. Copy the return value onto argument 0
  • 2. Restores the segment pointers of the caller
  • 3. Clears the stack
  • 4. Sets SP for the caller
  • 5 Jumps to the return address within the caller's code
  • This is complicated, but this is not a surprise, because we are creating a little brain. It has the capacity to do one function, put it on hold, and then return to it when it's done. This is sophisticated, no wonder the implementation is non trivial.
  • Very simple from the abstract view: call function, and get the result, but very complicated behind the scenes

Unit 2.5: Function Call and Return: Run-time Simulation

  • example of calling factorial of 3, run time simulation

Unit 2.6: Function Call and Return Implementation

  • Handling call:
    • push returnAddress (using a label)
    • push LCL, ARG, THIS, THAT // save of the caller
    • ARG = SP - 5 - nArgs // Reposition ARG
    • LCL = SP // Reposition LCL
    • goto functionName // Transfers control to the called function
    • (returnAddress) // Declare a label for the return-address

Unit 2.7: VM Implementation on the Hack Platform

  • VM programming convention: One file must be named Main.vm, with one function named main
  • Bootstrap code: SP=256, Call Sys.init
  • Special symbols

Unit 2.8: VM Translator: Proposed Implementation

Lecture Slides

Chapter 8 from the course book