Assembler, Part 3

April 23, 2014

We studied a simple assembler for a hypothetical computer in the two previous exercises. Today we finish our look at the assembler by writing a program that produces neat listings, like this one for our sample program:

# print sum of input numbers (terminated by zero)

000:  03010        ld    zero # initialize sum to zero          
001:  04011        st    sum                                    
002:  01000   loop get        # read a number                   
003:  08007        jz    done # no more input if number is zero 
004:  05011        add   sum  # add input to accumulated sum    
005:  04011        st    sum  # store new value back in sum     
006:  09002        j     loop # go back and read another number 

007:  03011   done ld    sum  # print sum                       
008:  02000        put                                          
009:  10000        halt                                         

010:  00000   zero const 0                                      
011:  00000   sum  const

The listing shows the memory address in the first column, the contents of memory at the beginning of the program in the second column, the mnemonic label in the third column, the opcode in the fourth column, the object of the operation in the fifth column, and the comment in the sixth column.

Your task is to write a program that produces assembler listings. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

About these ads

Pages: 1 2

One Response to “Assembler, Part 3”

  1. (defn listing [C code]
      (let [mem (:M (load-asm C code))]
        (println
          (second
            (reduce (fn [[counter text] e]
                      (let [pref (if (whitespace? e)
                                   ""
                                   (format "%03d: %s\t" counter (aget (:M C) counter)))
                            new-counter (if (whitespace? e) counter (inc counter))]
                        [new-counter (str text "\n" pref e)]))
                    [0 ""]
                    (clojure.string/split code #"\n"))))))
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 632 other followers

%d bloggers like this: