6.5.Hack汇编器开发

\(6.5.\)Developing a Hack Assembler

1.Start reding a file

  In general, this part:

  • Need to be able to read the input and break it into parts.
  • Doesn't need to understand what the command means or how it will be translated into machine language.
  • Need to understand the format of the input language and how it breaks into different components.

  In detail, we may divide it into several parts:

  1. Read a file with a given name.

    • You may want a constructor to be able to accept the file name and then open the file for reading.
  2. Move to next command in the file:

    1. Are we finished? boolean hasMoreCommands()
    2. Get the next command: void advance()
    3. Read into one line into some kind of string.
    4. Skip white space including comments.
  3. Get the fields of the current command

    • Type of command (A, C, or label)

2.Translating mnemonic to code

  In general, this part:

  • Don't need to worry about how the mnemonic fields were obtained.

    • No need to know what part of input line it is, etc.

  In detail, we:

  1. Ask the parser to give us the string that corresponds to each part of the field.
  2. Once we get the three string, we go to the code object to translate each one of them separately according to the known table.
  3. Concatenate the output together.

3.The symbol table

  In general, this part:

  • Don't need to know what the symbols mean.
  • Need to maintain the association between a symbol and a memory address.

  In detail, we need to be able to:

  1. Create an new empty table
  2. Add a (symbol, address) pair to the table
  3. Does the table contain a given symbol?
  4. What is the address associated with a given symbol?

  And do the following things:

  1. Create a new empty table

  2. Add all the pre-defined symbols to the table

  3. While reading the input, add labels and new variables to the table

    • Labels: when you see a "(xxx)" command,add "xxx" and the address of the next machine language command

      • Comment 1: this requires maintaining this running address (line number).
      • Comment 2: this may need to be done in a first pass
    • Variables: when you see an "@xxx" command, where "xxx" is not a number and not already in the table, add "xxx" and the next free address for variable allocation