Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

26 Commits

Folders and files

Repository files navigation

Nand2Tetris

My implementations for the Nand to Tetris course (The Elements of Computing Systems by Noam Nisan and Shimon Schocken).

The repository covers the computer system from basic logic gates up through a two-pass assembler, stack-based virtual machine, and high-level programs:

  • Projects 1–5: Hardware platform built in HDL (logic gates, ALU, RAM, CPU, and computer architecture).
  • Projects 6–8: Software toolchain built in C++ (two-pass assembler and stack-based VM translator).
  • Project 9: High-level program written in Jack.

Projects Overview

Hardware (HDL)

  • Project 1: Boolean Logic
    Elementary logic gates built from primitive Nand chips: Not, And, Or, Xor, Mux, DMux, along with multi-bit and multi-way variants (Not16, And16, Or16, Mux16, Or8Way, Mux4Way16, Mux8Way16, DMux4Way, DMux8Way).

  • Project 2: Boolean Arithmetic & ALU
    Adders (HalfAdder, FullAdder, Add16, Inc16) and the Hack Arithmetic Logic Unit (ALU.hdl). The ALU implements 18 operations using 6 control bits (zx, nx, zy, ny, f, no) and computes status flags for zero (zr) and negative (ng).

  • Project 3: Memory
    Clocked sequential chips starting from 1-bit memory (Bit) and registers (Register), up through RAM8, RAM64, RAM512, RAM4K, and RAM16K. Also includes the 16-bit Program Counter (PC.hdl) with reset, load, and increment support.

  • Project 4: Machine Language
    Low-level programs written in Hack assembly:

    • Mult2.asm: Integer multiplication using repeated addition (R2 = R0 * R1).
    • Fill.asm: Real-time I/O program that polls the keyboard (KBD) and paints the screen (SCREEN) black when a key is pressed, clearing it back to white when released.
  • Project 5: Computer Architecture
    Integrates the CPU, memory, and ROM into a 16-bit Von Neumann computer:

    • CPU.hdl: Instruction decoding, ALU integration, A/D register multiplexing, and jump evaluation against ALU status flags.
    • Memory.hdl: Unified memory space combining 16K data RAM, 8K screen memory map, and the keyboard register.
    • Computer.hdl: Top-level chip wiring together CPU, Memory, and ROM32K.

Software (C++)

  • Project 6: Assembler
    A two-pass cross-assembler written in C++ that translates symbolic Hack assembly (.asm) into 16-bit binary machine code (.hack).

    • Architecture: Structured modularly into Parser (tokenizing lines, stripping comments and whitespace), Code (translating assembly mnemonics to binary), and SymbolTable (tracking labels and variable addresses).
    • Instruction Handling:
      • A-Instructions (@value or @symbol): Converts numeric constants directly to binary addresses (0vvvvvvvvvvvvvvv), and resolves symbolic references via the symbol table.
      • C-Instructions (dest=comp;jump): Parses destination registers, ALU computation codes, and jump conditions into 16-bit words (111accccccdddjjj). Destination bits are generated using bitmask operations (M=1, D=2, A=4), while comp and jump mnemonics are resolved via hash table lookups.
    • Two-Pass Symbol Resolution:
      • Pass 1: Scans the source to identify label declarations (LABEL). Labels are recorded in the symbol table mapped to the ROM address of the next instruction, without advancing the instruction counter.
      • Pass 2: Re-reads the file to resolve and encode all instructions. Predefined symbols (R0–R15, SCREEN, KBD, SP, LCL, etc.) are recognized automatically, while user variables are dynamically assigned sequential RAM addresses starting at memory offset 16.
    • Implementation: Uses std::string_view for zero-allocation mnemonic parsing, std::unordered_map for $O(1)$ lookups, and std::bitset<16> to format the binary output lines.
  • Project 7: VM I (Stack Arithmetic & Memory)
    The first stage of the Virtual Machine translator, implementing the backend that translates stack-based VM bytecode commands into target Hack assembly:

    • Stack Engine: Emulates a stack machine on the Hack architecture. Pushing and popping manipulate the stack pointer (SP at RAM[0]) and transfer values through the CPU's D register.
    • Arithmetic & Logical Commands:
      • Unary operations (neg, not) operate in-place on the top stack element.
      • Binary arithmetic and bitwise operations (add, sub, and, or) pop the top operand into D and combine it with the second operand at *(SP - 1).
      • Comparisons (eq, gt, lt) compute x - y and branch using generated labels (CONDITIONAL_i, CONTINUE_i) to push -1 (true) or 0 (false) back onto the stack.
    • Memory Segment Virtualization: Maps 8 virtual memory segments into the physical RAM architecture:
      • constant: Directly pushes literal values onto the stack.
      • local, argument, this, that: Dynamic segments accessed by adding the index offset to the segment base pointer stored in RAM (LCL, ARG, THIS, THAT).
      • temp: Mapped to a fixed 8-word hardware buffer (RAM[5]–RAM[12]).
      • pointer: Directly accesses THIS (pointer 0) or THAT (pointer 1) for base address manipulation.
      • static: Global variables mapped to assembly symbols (FileName.index), which the assembler automatically assigns to RAM[16–255].

*- Project 8: VM II (Program Control & Functions)
Completes the VM translator by adding program flow, function declarations, calling conventions, and recursive execution:

  • Program Flow: Implements unconditional jumps (goto label), conditional branching (if-goto label), and target markers (label label). Labels are scoped with the enclosing function name (FileName.functionName$label) to prevent naming collisions across files.
  • Function Calling Protocol & Stack Frames: Implements a full calling convention enabling nested and recursive subroutine calls:
    • call functionName numArgs: Pushes a unique return address label (functionName$ret.i), pushes the caller's segment pointers (LCL, ARG, THIS, THAT) to save context, repositions ARG = SP - 5 - numArgs and LCL = SP, and jumps to the function label.
    • function functionName numVars: Emits the function entry label and initializes numVars local variables to 0 by pushing 0s onto the stack.
    • return: Captures the caller's frame base pointer (LCL), saves the return address, copies the return value to *ARG, reclaims the stack space by resetting SP = ARG + 1, and restores the caller's THAT, THIS, ARG, and LCL segment pointers using decremental offsets from the saved frame base before jumping back to the return address.
  • Bootstrap Code & Multi-File Support:
    • Injects runtime initialization code that sets SP = 256 and calls Sys.init to start program execution.
    • Uses C++17 std::filesystem::recursive_directory_iterator to traverse project directories, translating multiple .vm modules into a single unified .asm output file (supporting complex programs like FibonacciElement and NestedCall).

High-Level Language

  • Project 9: Jack Application
    Application written in Jack (Main.jack), the high-level object-based language designed for the platform, demonstrating output via the Jack OS library (Output.printString).

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages