teaching machines

CS 352 Lecture 20 – Assembler

October 24, 2016 by . Filed under cs352, fall 2016, lectures.

Dear students,

In homework, you’ve been working on chapters 1, 2, and 3 of our textbook. Your next homework will be chapter 5, which involves tying everything you’ve built into a complete computer, albeit in HDL form. In lecture, we’ve hit upon chapter 4, which covers assembly for this computer. Today we discuss chapter 6, which involves writing an assembler. Our assembler will turn assembly into Hack machine code, whose every instruction becomes a configuration of input pins to CPU.

We’ll first inspect what Hack machine code instructions look like. They come in two flavors: address instructions (A instructions) and compute instructions (C instructions). The A instructions are binary versions of the @ instructions of assembly. The C instructions are a composition of several bit patterns.

We can write our assembler in any language we want. Of course, if we didn’t already have a machine, we’d be writing it in machine code. But we do have an existing machine, and we’ll use Ruby to turn assembly in machine code.

Here’s your TODO list:

See you next class!

Sincerely,

P.S. Here’s the code we wrote together…

assembler.rb

#!/usr/bin/env ruby

symbols = {
  'R0' => 0,
  'R1' => 1,
  'R2' => 2,
  'R3' => 3,
  'R4' => 4,
  'R5' => 5,
  'R6' => 6,
  'R7' => 7,
  'R8' => 8,
  'R9' => 9,
  'R10' => 10,
  'R11' => 11,
  'R12' => 12,
  'R13' => 13,
  'R14' => 14,
  'R15' => 15,
  'KBD' => 24576,
  'SCREEN' => 16384,
  'SP' => 0,
  'LCL' => 1,
  'ARG' => 2,
  'THIS' => 3,
  'THAT' => 4,
}

src = File.read(ARGV[0])

src.gsub!(/\/\/.*/, '')
src.gsub!(/\n{2,}/, '')
src.gsub!(/^ +/, '')
src.gsub!(/ +$/, '')

instructions = []
src.lines.each do |line|
  if line =~ /\(([A-Za-z].*)\)/
    label = $1
    symbols[label] = instructions.size
  else
    instructions << line
  end
end