A Java implementation of the Hack Assembler from the Nand2Tetris course.
This project translates Hack assembly language (.asm) programs into 16-bit binary machine code (.hack), supporting symbols, labels, and variables.
- Two-pass assembly:
- First pass: Builds the symbol table and resolves labels.
- Second pass: Translates A- and C-instructions into binary.
- Predefined symbols (
R0βR15,SP,LCL,ARG,THIS,THAT,SCREEN,KBD). - Custom variables starting at RAM address 16.
- Parser that strips comments and whitespace.
- Code module that maps mnemonics to binary codes.
- Symbol table for managing predefined and user-defined symbols.
βββ Main.java # Entry point, assembles given .asm files
βββ Assembler.java # Core assembler logic
βββ Parser.java # Cleans input, parses commands
βββ Instruction_Category.java # Enum for A, C, and LABEL instructions
βββ Code.java # Converts mnemonics to binary codes
βββ SymbolTable.java # Handles predefined + user-defined symbols
βββ *.asm # Example Hack assembly programs
βββ *.hack # Generated binary machine code
- Cleaning the Code
- Cleans the input file from any whitespaces or comments.
- First Pass
- Reads the assembly file and records all labels
(LABEL)with their corresponding ROM addresses in the symbol table.
- Reads the assembly file and records all labels
- Second Pass
- Translates instructions line by line:
@valueβ A-instruction (direct address or symbol lookup).dest=comp;jumpβ C-instruction (binary translation ofcomp,dest, andjump).
- Translates instructions line by line:
- Output
- Writes a
.hackfile containing the 16-bit binary machine code.
- Writes a
Input (Add.asm):
@2
D=A
@3
D=D+A
@0
M=DOutput (Add.Hack):
0000000000000010
1110110000010000
0000000000000011
1110000010010000
0000000000000000
1110001100001000
- Nand2Tetris Course
- The Elements of Computing Systems (Noam Nisan & Shimon Schocken)