当前位置: 首页>>代码示例>>Python>>正文


Python Parser.commandType方法代码示例

本文整理汇总了Python中Parser.Parser.commandType方法的典型用法代码示例。如果您正苦于以下问题:Python Parser.commandType方法的具体用法?Python Parser.commandType怎么用?Python Parser.commandType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Parser.Parser的用法示例。


在下文中一共展示了Parser.commandType方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: second_pass

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
def second_pass(path, symbol_table):
    p = Parser(path)
    code = Code()
    ram_address = 16
    hack = []
    while(p.hasMoreCommands()):
        command_type = p.commandType()
        if (command_type == CommandType.L):
            p.advance()
            continue
        elif (command_type == CommandType.C):
            dest = code.dest(p.dest())
            comp = code.comp(p.comp())
            jump = code.jump(p.jump())
            command = int("111" + comp + dest + jump, 2)
        else:  # command_type == CommandType.A
            symbol = p.symbol()
            if symbol.isdigit():
                address = int(symbol)
            else:
                if not symbol_table.contains(symbol):
                    symbol_table.add_entry(symbol, ram_address)
                    ram_address += 1
                address = symbol_table.get_address(symbol)
            command = address
        command = format(command, '016b')
        hack.append(command)
        p.advance()
    return hack
开发者ID:bendanon,项目名称:n2t-proj6,代码行数:31,代码来源:Main.py

示例2: first_pass

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
def first_pass(path):
    p = Parser(path)

    symbol_table = SymbolTable()
    n = 0
    while(p.hasMoreCommands()):
        command_type = p.commandType()
        if(command_type == CommandType.L):
            symbol_table.add_entry(p.symbol(), n)
        else:
            n += 1
        p.advance()
    return symbol_table
开发者ID:bendanon,项目名称:n2t-proj6,代码行数:15,代码来源:Main.py

示例3: Parser

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
        action='store_true',
        help='set output to verbose')

arg_parser.add_argument('--out',
        dest='output_filename',
        default='',
        help='set output file')

args = arg_parser.parse_args()

p = Parser(args.filename)

output = []

while p.hasMoreCommands():
    t = p.commandType()
    if t == 'A_COMMAND':
        a = int(p.symbol())
        byte = '0{:015b}'.format(a)
    elif t == 'C_COMMAND':
        byte = '111{}{}{}'.format(
                comp(p.comp()),
                dest(p.dest()),
                jump(p.jump()))
        pass
    elif t == 'L_COMMAND':
        byte = ('l', p.symbol())
    else:
        raise Error
    output.append((byte, p.assembly()))
    p.advance()
开发者ID:Jsearle01,项目名称:the_elements_of_computing_systems,代码行数:33,代码来源:no_symbols_assembler.py

示例4: Parser

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
@author: Kyle June
"""
import sys
from Parser import Parser
import Code
from SymbolTable import SymbolTable

asmFilename = sys.argv[1]

# This goes through the file and adds the address for each label to the symbol table.
parser = Parser(asmFilename)
symbolTable = SymbolTable()
romAddress = 0
while parser.hasMoreCommands():
    parser.advance()
    if parser.commandType() == "L_COMMAND":
        symbolTable.addEntry(parser.symbol(), romAddress)
    else:
        romAddress += 1

# This opens the file that will be written to.
hackFilename = asmFilename[:-3] + "hack"
hackFile = open(hackFilename, "w")

# This writes the translated code to the hack file.
parser.restart()
ramAddress = 16
while parser.hasMoreCommands():
    parser.advance()
    commandType = parser.commandType()
    if commandType == "C_COMMAND":
开发者ID:KyleJune,项目名称:HackAssembler,代码行数:33,代码来源:Assembler.py

示例5: __init__

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
class CodeWriter:


    def __init__(self, parser):
        '''
        Opens the output file and gets ready to write into it
        :param parser object to use
        :return:
        '''
        self.parser = Parser()
        self.eqCounter = 0 # appended to end of EQUAL labels so they are unique
        self.memoryMappedRegisters = {"local": "LCL",
                       "argument": "ARG",
                       "this": "R3",
                       "that": "R4",
                       "pointer": "R3",
                        "temp": "R5"}

        self.currentVMFile = ""
        self.file = None





    def setCurrentVMFile(self, fileName):
        '''
        Changes VM file that is currently being translated
        :param fileName:
        :return:
        '''
        self.currentVMFile = fileName[:-3]




    def assembleVMCommand(self, command):
        self.parser.setInstruction(command)
        if self.parser.commandType(command) == 0:
            return self.translateArithmetic(command)
        elif self.parser.commandType(command) in range(1,3):
            return self.translatePushPop(command)




    def translateArithmetic(self, command):
        '''
        Writes the assembly code that is the translation of the given
        arithmetic command
        :param command: command string
        :return: list where each element is one line of assembly code

        :todo "sub", "neq", "gt", "lt", "and", "or", "not"]
        '''
        self.parser.setInstruction(command)
        if self.parser.currentInstructionType != self.parser.C_ARITHMETIC:
            raise RuntimeError("translate arithmetic cannot translate non-arithmetic type")

        if command == "add":
            return ["@SP", "M=M-1", "A=M", "D=M", "@SP", "M=M-1", "A=M", "M=D+M",
                             "@SP", "M=M+1"]
        elif command == "sub":
            return ["@SP", "A=M", "A=A-1", "D=M", "A=A-1", "M=M-D", "@SP", "M=M-1"]
        elif command == "neg":
            return ["@SP", "A=M", "A=A-1", "M=-M"]
        elif command == "and":
            return ["@SP", "A=M", "A=A-1", "D=M", "A=A-1", "M=D&M", "@SP", "M=M-1"]
        elif command == "or":
            return ["@SP", "A=M", "A=A-1", "D=M", "A=A-1", "M=D|M", "@SP", "M=M-1"]
        elif command == "not":
            return ["@SP", "A=M", "M=!M"]
        elif command == "gt":
            self.eqCounter += 1
            return ["@SP", "A=M", "A=A-1", "D=M", "A=A-1", "D=M-D", "@GT" + str(self.eqCounter), "D;JGT", "@NGT" + str(self.eqCounter),
                    "0;JEQ", "(GT"   + str(self.eqCounter) + ")", "@SP", "A=M", "A=A-1", "A=A-1", "M=-1", "@SP", "M=M-1",
                    "@CONTINUE" + str(self.eqCounter), "0;JEQ", "(NGT"  + str(self.eqCounter) + ")", "@SP", "A=M", "A=A-1",
                    "A=A-1", "M=0", "@SP", "M=M-1", "@CONTINUE" + str(self.eqCounter), "0;JEQ", "(CONTINUE"  + str(self.eqCounter) + ")"]
        elif command == "lt":
            self.eqCounter += 1
            return ["@SP", "A=M", "A=A-1", "D=M", "A=A-1", "D=M-D", "@LT" + str(self.eqCounter), "D;JLT",
                    "@NLT" + str(self.eqCounter), "0;JEQ", "(LT"   + str(self.eqCounter) + ")", "@SP", "A=M", "A=A-1",
                    "A=A-1", "M=-1", "@SP", "M=M-1", "@CONTINUE" + str(self.eqCounter), "0;JEQ",
                    "(NLT"  + str(self.eqCounter) + ")", "@SP", "A=M", "A=A-1", "A=A-1", "M=0", "@SP", "M=M-1",
                    "@CONTINUE" + str(self.eqCounter), "0;JEQ", "(CONTINUE"  + str(self.eqCounter) + ")"]
        elif command == "eq":
            self.eqCounter += 1
            return ['@SP', 'M=M-1', 'A=M', 'D=M', '@SP', 'M=M-1', 'A=M', 'D=D-M', '@EQUAL' + str(self.eqCounter), 'D;JEQ', '@NOTEQUAL' + str(self.eqCounter), '0;JEQ',
                     '(EQUAL' + str(self.eqCounter) + ')', '@SP', 'A=M', 'M=-1', '@CONTINUE'  + str(self.eqCounter),
                                '0;JEQ', '(NOTEQUAL' + str(self.eqCounter) + ')', '@SP', 'A=M', 'M=0',
                     '(CONTINUE' + str(self.eqCounter) + ')', '@SP', 'M=M+1']




    def translatePushPop(self, command):
        '''
        Return assembly code for a given push/pop VM command, ie push local 2
        Calls translatePush or translatePop depending on type
        :param command:
#.........这里部分代码省略.........
开发者ID:dserver,项目名称:Nand2Tetris,代码行数:103,代码来源:CodeWriter.py

示例6: main

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
def main(args):
    '''
    You can set vm_file_path to be either a folder (and then an asm file
    with the folder source_file will be created in the folder) or set it to be
    a vm file (and then an asm file with the file source_file will be created
    in the same location)
    '''
    if len(args) != 1:
        print "Usage: (python) Main.py [<.vm file path>|<source dir path>]"
        return

    vm_file_path = args[0]

    # vm_file_path = "Input/StackArithmetic/SimpleAdd/SimpleAdd.vm"
    # vm_file_path = "Input/StackArithmetic/StackTest/StackTest.vm"
    # vm_file_path = "Input/MemoryAccess/BasicTest/BasicTest.vm"
    # vm_file_path = "Input/MemoryAccess/PointerTest/PointerTest.vm"
    # vm_file_path = "Input/MemoryAccess/StaticTest/StaticTest.vm"
    # vm_file_path = "Input/ProgramFlow/BasicLoop/BasicLoop.vm"
    # vm_file_path = "Input/ProgramFlow/FibonacciSeries/FibonacciSeries.vm"
    # vm_file_path = "Input/FunctionCalls/SimpleFunction/SimpleFunction.vm"

    init_code_required = False
    source_file_paths = []
    sep = '/' if '/' in vm_file_path else os.sep

    if not vm_file_path.endswith(".vm"):
        source_file_names = [file_name for file_name in
                             os.listdir(vm_file_path) if
                             file_name.endswith('.vm')]
        source_file_paths += [os.path.join(vm_file_path, file_name) for
                              file_name in source_file_names]
        init_code_required = 'Sys.vm' in source_file_names
        asm_file_name = "{0}.asm".format(vm_file_path.split(sep)[-2])
        asm_file_path = os.path.join(vm_file_path, asm_file_name)
    else:
        source_file_paths = [vm_file_path]
        asm_file_path = vm_file_path.replace(".vm", ".asm")

    cw = CodeWriter(asm_file_path)
    if init_code_required:
        cw.writeInit()
        cw.writeFinishLoop()

    for source_file in source_file_paths:
        cw.setFileName(source_file)
        p = Parser(source_file)

        while(p.hasMoreCommands()):
            cmdType = p.commandType()

            if(cmdType == CommandType.C_ARITHMETIC):
                cw.writeArithmetic(p.arg1())

            elif(cmdType == CommandType.C_PUSH or
                 cmdType == CommandType.C_POP):
                cw.writePushPop(cmdType, p.arg1(), p.arg2())

            elif(cmdType == CommandType.C_LABEL):
                cw.writeLabel(p.arg1())

            elif(cmdType == CommandType.C_GOTO):
                cw.writeGoto(p.arg1())

            elif(cmdType == CommandType.C_IF):
                cw.writeIf(p.arg1())

            elif(cmdType == CommandType.C_CALL):
                cw.writeCall(p.arg1(), p.arg2())

            elif(cmdType == CommandType.C_FUNCTION):
                cw.writeFunction(p.arg1(), p.arg2())

            elif(cmdType == CommandType.C_RETURN):
                cw.writeReturn()

            p.advance()

    cw.Close()
开发者ID:bendanon,项目名称:n2t-proj7,代码行数:81,代码来源:Main.py

示例7: exit

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
	exit(1)
finally:
	outFile.close()



writer = CodeWriter(outPath)

for f in vmNames:
	fn = path.basename(f)
	print "Working on:",fn
	writer.setFileName(fn)
	parser = Parser(f)
	while parser.hasMoreCommands():
		parser.advance()
		if parser.commandType() == "C_ARITHMETIC":
			writer.writeArithmetic(parser.arg1())
		elif parser.commandType() == "C_PUSH":
			writer.writePushPop("PUSH", parser.arg1(), parser.arg2())
		elif parser.commandType() == "C_POP":
			writer.writePushPop("POP", parser.arg1(), parser.arg2())
		elif parser.commandType() == "C_LABEL":
			writer.writeLabel(parser.arg1())
		elif parser.commandType() == "C_GOTO" or parser.commandType() == "C_IF-GOTO":
			writer.writeGoto(parser.commandType()[2:], parser.arg1())
		elif parser.commandType() == "C_FUNCTION":
			writer.writeFunct(parser.arg1(), parser.arg2())
		elif parser.commandType() == "C_CALL":
			writer.writeCall(parser.arg1(), parser.arg2())
		elif parser.commandType() == "C_RETURN":
			writer.writeReturn()
开发者ID:joeboxes,项目名称:csci498-jkeyoth,代码行数:33,代码来源:translator.py

示例8: __init__

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
class CodeWriter:


    def __init__(self, parser):
        '''
        Opens the output file and gets ready to write into it
        :param parser object to use
        :return:
        '''
        self.parser = Parser()
        self.eqCounter = 0 # appended to end of EQUAL labels so they are unique
        self.callerCounter = 0 # same as eqCounter but for return address labels
        self.memoryMappedRegisters = {"local": "LCL",
                       "argument": "ARG",
                       "this": "R3",
                       "that": "R4",
                       "pointer": "R3",
                        "temp": "R5"}

        self.currentVMFile = ""
        self.file = None
        self.currentFunction = ""





    def setCurrentVMFile(self, fileName):
        '''
        Changes VM file that is currently being translated
        :param fileName:
        :return:
        '''
        self.currentVMFile = fileName[:-3]

    def setCurrentFunction(self, function):
        '''
        Set function scope to what is being compiled. Used for label, if-goto, goto, etc.
        :param function:
        :return:
        '''

        self.currentFunction = function



    def assembleVMCommand(self, command):
        self.parser.setInstruction(command)
        if self.parser.commandType(command) == self.parser.C_ARITHMETIC:
            return self.translateArithmetic(command)


        elif self.parser.commandType(command) in [self.parser.C_PUSH, self.parser.C_POP]:
            return self.translatePushPop(command)


        elif self.parser.commandType(command) == self.parser.C_FUNCTION:
            return self.translateFunction(self.parser.arg2())


        elif self.parser.commandType(command) == self.parser.C_CALL:
            return self.translateCall(self.parser.arg1(), int(self.parser.arg2()))


        elif self.parser.commandType(command) == self.parser.C_RETURN:
            return self.translateReturn()


        elif self.parser.commandType(command) == self.parser.C_LABEL:
            return self.translateLabel(self.parser.arg1())


        elif self.parser.commandType(command) == self.parser.C_IF:
            return self.translateIfGoto(self.parser.arg1())


        elif self.parser.commandType(command) == self.parser.C_GOTO:
            return self.translateGoto(self.parser.arg1())





    def translateArithmetic(self, command):
        '''
        Writes the assembly code that is the translation of the given
        arithmetic command
        :param command: command string
        :return: list where each element is one line of assembly code

        :todo "sub", "neg", "gt", "lt", "and", "or", "not"]
        '''
        self.parser.setInstruction(command)
        if self.parser.currentInstructionType != self.parser.C_ARITHMETIC:
            raise RuntimeError("translate arithmetic cannot translate non-arithmetic type")

        if command == "add":
            return ["@SP", "M=M-1", "A=M", "D=M", "@SP", "M=M-1", "A=M", "M=D+M",
                             "@SP", "M=M+1"]
        elif command == "sub":
#.........这里部分代码省略.........
开发者ID:dserver,项目名称:Nand2Tetris,代码行数:103,代码来源:CodeWriter.py

示例9: open

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
#open output file, fail nicely if it fails
try:
	outFile = open(outPath, "w")
	
except:
	print outPath + ": file could not be opened"
	exit(1)
finally:
	outFile.close()



writer = CodeWriter(outPath)

for f in vmNames:
	fn = path.basename(f)
	print "Working on:",fn
	writer.setFileName(fn)
	parser = Parser(f)
	while parser.hasMoreCommands():
		parser.advance()
		if parser.commandType() == "C_ARITHMETIC":
			writer.writeArithmetic(parser.arg1())
		if parser.commandType() == "C_PUSH":
			writer.writePushPop("PUSH", parser.arg1(), parser.arg2())
		if parser.commandType() == "C_POP":
			writer.writePushPop("POP", parser.arg1(), parser.arg2())
			
writer.close()
print inPath,"=>",outPath
			
开发者ID:joeboxes,项目名称:csci498-jkeyoth,代码行数:32,代码来源:translator.py

示例10: Parser

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]

infile = sys.argv[1]  # Sys.argv is the system argument list object

outfile = infile.replace(".asm", ".hack")
parse = Parser(infile)
outfilecontents = ""
code = Code()
sym = Symbol()
i = 0
numOfNonLabelSymbols = 0
while parse.hasMoreCommands():
    parse.advance()
    parse.output()
    parse.stripwhitespace()
    if len(parse.parsedline) != 0 and parse.parsedline != "\n" and parse.commandType() == 2:
        if not sym.contains(parse.symbol()):
            sym.addEntry(parse.symbol(), str(i))
    if len(parse.parsedline) != 0 and parse.parsedline != "\n" and parse.commandType() != 2:
        i += 1

parse = Parser(infile)
while parse.hasMoreCommands():
    parse.advance()
    parse.output()
    parse.stripwhitespace()
    if (
        len(parse.parsedline) != 0
        and parse.parsedline != "\n"
        and parse.commandType() == 0
        and not sym.contains(parse.symbol())
开发者ID:joshWretlind,项目名称:CSCI410-ElementsOfComputingSystems,代码行数:32,代码来源:Assembler.py

示例11: Parser

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import commandType [as 别名]
@author: Kyle June
'''
import sys
from Parser import Parser
import Code
from SymbolTable import SymbolTable

asmFilename = sys.argv[1]

# This goes through the file and adds the address for each label to the symbol table.
parser = Parser(asmFilename)
symbolTable = SymbolTable()
romAddress = 0
while parser.hasMoreCommands():
    parser.advance()
    if parser.commandType() == 'L_COMMAND':
        symbolTable.addEntry(parser.symbol(), romAddress)
    else:
        romAddress += 1

# This opens the file that will be written to.
hackFilename = asmFilename[:-3] + 'hack'
hackFile = open(hackFilename, 'w')

# This writes the translated code to the hack file.
parser.restart()
ramAddress = 16
while parser.hasMoreCommands():
    parser.advance()
    commandType = parser.commandType()
    if commandType == 'C_COMMAND':
开发者ID:KyleJune,项目名称:HackAssembler,代码行数:33,代码来源:ModAssembler.py


注:本文中的Parser.Parser.commandType方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。