A Python implementation of an assembler for the Hack computer platform, converting Hack assembly language into machine code. This assembler is part of the Nand to Tetris course.
- ✨ Full support for Hack assembly language syntax
- 🏷️ Symbol handling (variables and labels)
- 🔄 Two-pass assembly process
- 🎯 Clean, modular code structure
- 📝 Detailed error messages
- 🧪 Comprehensive testing suite
- Python 3.9 or higher
- No external dependencies required
- Clone the repository:
git clone https://github.com/yourusername/hack-assembler.git
cd hack-assembler- (Optional) Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activateRun the assembler from the command line:
python -m assembler.main your_program.asmThis will create your_program.hack containing the machine code.
from assembler import Parser, Code
from assembler.file_handler import read_file, write_output_file
from assembler.symbol_table import initialize_symbol_table, first_pass, second_pass
# Read assembly file
assembly_code = read_file()
# Process symbols
symbol_table = initialize_symbol_table()
symbol_table = first_pass(assembly_code, symbol_table)
processed_code, symbol_table = second_pass(assembly_code, symbol_table)
# Generate machine code
parser = Parser(processed_code)
code_generator = Code()
machine_code = []
while parser.has_more_lines:
parser.advance()
# Process instructions...assembler/
│
├── __init__.py # Package initialization
├── main.py # Main entry point
├── constants.py # Constants and patterns
├── code.py # Binary code generation
├── parser.py # Instruction parsing
├── symbol_table.py # Symbol management
└── file_handler.py # File I/O operations
// Adds 1 + 2
@1
D=A
@2
D=D+A
@3
M=D0000000000000001
1110110000010000
0000000000000010
1110000010010000
0000000000000011
1110001100001000
Run the test suite:
python -m pytest tests/The Hack assembly language supports three types of instructions:
-
A-instructions:
@value- Load a value or symbol into the A register
- Example:
@100,@LOOP
-
C-instructions:
dest=comp;jump- Compute a value and store it
- Example:
D=M+1,0;JMP
-
Labels:
(LABEL)- Define a symbol for jumps
- Example:
(LOOP)
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Based on the Nand to Tetris course
- Thanks to Noam Nisan and Shimon Schocken for the course materials
- All contributors and testers
Siladitya Samaddar - @silacode
Project Link: https://github.com/silacode/assembler