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:
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.
Move to next command in the file:
- Are we finished?
boolean hasMoreCommands()
- Get the next command:
void advance()
- Read into one line into some kind of string.
- Skip white space including comments.
- Are we finished?
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:
- Ask the parser to give us the string that corresponds to each part of the field.
- Once we get the three string, we go to the code object to translate each one of them separately according to the known table.
- 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:
- Create an new empty table
- Add a (symbol, address) pair to the table
- Does the table contain a given symbol?
- What is the address associated with a given symbol?
And do the following things:
Create a new empty table
Add all the pre-defined symbols to the table
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