我创建了应该将机器语言转换为汇编语言的代码,但是当我尝试从命令提示符运行它时,我不断收到错误消息。我收到的错误是:
Traceback <most recent call last>:
File "Assembler.py", line 102, in <module>
parser.advance()
File "Assembler.py", line 15, in advance
self.command = self.asm_file[self.index]
IndexError: list index out of range
我不太确定为什么它超出了范围。我在命令提示符中输入的是:
python Assembler.py MyFile.asm
有人可以看看我下面的代码并帮助我弄清楚它为什么给我这个吗?
class Parser:
def __init__(self, filename):
self.asm_file = [line for line in open(filename)]
self.index = 0
def hasMoreCommands(self):
return self.index < len(self.asm_file)
def advance(self):
self.index += 1
if self.index == len(self.asm_file):
return
self.command = self.asm_file[self.index]
self.command = self.removeCommentsAndSpaces(self.command)
if not self.command:
self.advance()
这些块之间只有更多的代码定义,错误消息中引用的第 102 行是下一个块的第 10 行。
if __name__ == '__main__':
import sys
if len(sys.argv) == 1:
print 'need filename'
sys.exit(-1)
table = SymbolTable()
parser = Parser(sys.argv[1])
parser.advance()
line = 0
while parser.hasMoreCommands():
if parser.commandType() == 'L_COMMAND':
table.addEntry(parser.symbol(), line)
else:
line += 1
parser.advance()
code = Code()
parser = Parser(sys.argv[1])
parser.advance()
var_stack = 16
while parser.hasMoreCommands():
cmd_type = parser.commandType()
if cmd_type == 'A_COMMAND':
number = 32768
try:
addr = int(parser.symbol())
except:
if table.contains(parser.symbol()):
addr = table.getAddress(parser.symbol())
else:
table.addEntry(parser.symbol(), var_stack)
addr = var_stack
var_stack += 1
bin_number = bin(number | addr)[3:]
assembly = '0' + bin_number
print assembly
elif cmd_type == 'C_COMMAND':
assembly = '111'
assembly += code.comp(parser.comp())
assembly += code.dest(parser.dest())
assembly += code.jump(parser.jump())
print assembly
parser.advance()