v3 VM: Closures and GC

Lesson, slides, and applied problem sets.

View Slides

Lesson

v3 VM + GC: Closures and Heap Objects

Why this module exists

Closures, arrays, and maps require heap allocation. The VM must track and reclaim memory explicitly with a mark-and-sweep GC.


1) Heap objects

Objects on the heap:

  • arrays
  • maps

Values store pointers to heap objects.


2) Mark-and-sweep

GC steps:

  1. Mark reachable objects from roots
  2. Sweep unreachable objects from the heap list

Roots include:

  • VM stack values
  • global and local environments
  • captured environments inside closures

3) Closures

A closure value stores:

  • the function bytecode
  • a pointer to the environment where it was created

Calls create a new local scope whose parent is the closure environment.


4) Runtime errors

Dynamic type mismatches are runtime errors, not compile errors.


Module Items