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


Python Parser.advance方法代码示例

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


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

示例1: second_pass

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [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 advance [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: main

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [as 别名]
    def main():

        print("******************************************")
        print("***          FileSet Report            ***")
        print("******************************************")
        print()

        fileORdir = Util.getCommandLineArgument(1)
        level = Util.getCommandLineArgument(2)
        files = FileSet(fileORdir, "hack")
        files.report()

        print()
        print("******************************************")
        print("***         Processing Report          ***")
        print("******************************************")
        print()

        while files.hasMoreFiles():
            inputFileSpec = files.nextFile()
            print("Processing: %s" % inputFileSpec)
            outputFileSpec = os.path.splitext(inputFileSpec)[0]+".dis"
            inputFile = open(inputFileSpec, "rU")
            outputFile = open(outputFileSpec, "w")
            parser = Parser(inputFile)
            while parser.hasMoreInstructions():
                parser.advance()
                if (parser.instructionType() == "A_TYPE"):
                    value = parser.value()
                    inst = Code.a_type(value)
                if (parser.instructionType() == "C_TYPE"):
                    dest = parser.dest()
                    comp = parser.comp()
                    jump = parser.jump()
                    destMnemonic = Code.destMnemonic(dest)
                    compMnemonic = Code.compMnemonic(comp)
                    jumpMnemonic = Code.jumpMnemonic(jump)
                    inst = Code.c_type(destMnemonic, compMnemonic, jumpMnemonic)
                if (parser.instructionType() == "INVALID"):
                    inst = Code.invalid_type()
                inst += Util.repeatedChar(" ", 20-len(inst))
                inst += "// %05i:" % parser.address()
                inst += " [%s]" % parser.hexInstruction()
                inst += " %s\n" % parser.parsedInstruction()
                outputFile.write(inst)
            outputFile.close()
            inputFile.close()

        print()
        print("Processing of file(s) complete.")
开发者ID:kmanzana,项目名称:nand2tetris,代码行数:52,代码来源:Main.py

示例4: main

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [as 别名]
def main():
    input_path = sys.argv[FILE_POS]
    if isdir(input_path):
        input_list = [ input_path + "/" +f for f in listdir(input_path)
            if (isfile(join(input_path, f))) and (f.endswith(".vm")) ]
        # check if we're getting a path or something else
        index = input_path.rfind("/")
        name = input_path[index + 1:]
        output_file_name = input_path + "/" + name + ".asm"
    else:
        input_list = [input_path]
        index = input_path.index(".vm")
        output_file_name = input_path[:index] + ".asm"

    code_writer = CodeWriter(output_file_name)

    for input_file in input_list:
        parser = Parser(input_file)
        code_writer.set_file_name(input_file)
        while parser.has_more_commands():
            command = parser.advance()
            if parser.command_type() == C_ARITHMETIC:
                code_writer.write_arithmetic(command)
            if (parser.command_type() == C_PUSH) or (parser.command_type() == C_POP):
                code_writer.write_push_pop(parser.command_type(), parser.arg1(), parser.arg2())

    code_writer.close()
开发者ID:hadarfranco,项目名称:From-NAND-to-Tetris,代码行数:29,代码来源:VMtranslator.py

示例5: int

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [as 别名]
    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()


if args.output_filename == '':
    args.output_filename = splitext(args.filename)[0] + '.hack'

if args.output_filename == '-':
    f = stdout
else:
    f = open(args.output_filename, "w")

for machine_code, assembly in output:
    if args.verbose:
        f.write('%s - %s' % (machine_code, assembly))
    else:
        f.write(machine_code)
开发者ID:Jsearle01,项目名称:the_elements_of_computing_systems,代码行数:33,代码来源:no_symbols_assembler.py

示例6: Parser

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [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()
开发者ID:KyleJune,项目名称:HackAssembler,代码行数:32,代码来源:Assembler.py

示例7: main

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [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

示例8: Assembler

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [as 别名]
class Assembler(object):

    def __init__(self, input_file_path):
        self.output_file = open(input_file_path.replace('.asm', '.hack'), 'w')

        """
        The ROM address is the address of the current instruction written in the
        .hack file. The first instruction is 0, second is 1, etc. Label is not a instruction.
        """
        self.current_rom_address = ROM_BASE_ADRESS

        self.parser = Parser(input_file_path)
        self.symbol_table = SymbolTable()

        """
        The RAM address of the next free memory that a new variable
        should be at.
        """
        self.next_free_var_address = VARIABLES_BASE_ADDRESS

    #Does the double pass assemble
    def assemble(self):
        self.first_pass()
        self.parser.start_over()
        self.second_pass()

    """
    Find Label commands adds all labels to the symbol table
    so jumps to labels yet-to-be-parsed could work.
    """
    def first_pass(self):
        self.current_rom_address = ROM_BASE_ADRESS
        while self.parser.has_more_commands():
            self.parser.advance()
            if self.parser.command_type() == self.parser.L_COMMAND:
                self.symbol_table.add_entry(self.parser.get_symbol(),
                                            self.current_rom_address)
            else:
                self.current_rom_address += INSTRUCTION_SIZE_IN_WORDS

    """
    Use the symbol table (if symbol is not a number) to get the
    address of the symbol. Create new variable if not in the table.
    """
    def _symbol_to_address(self, symbol):
        if symbol.isdigit():
            return int(symbol)
        if not self.symbol_table.contains(symbol):
            #new var
            self.symbol_table.add_entry(symbol, self.next_free_var_address)
            self.next_free_var_address += VARIABLE_SIZE_IN_WORDS
        return self.symbol_table.get_address(symbol)
    """
    Translate the A and C instructions to hack and write in the output file
    and skip labels
    """
    def second_pass(self):
        self.current_rom_address = ROM_BASE_ADRESS
        while self.parser.has_more_commands():
            self.parser.advance()
            #C instruction
            if self.parser.command_type() == self.parser.C_COMMAND:
                self._write_to_output(code.generate_c(self.parser.get_comp(),
                                                      self.parser.get_dest(),
                                                      self.parser.get_jump()))
            #A instruction
            elif self.parser.command_type() == self.parser.A_COMMAND:
                address = self._symbol_to_address(self.parser.get_symbol())
                self._write_to_output(code.generate_a(address))
            #Lable is not an instruction
            if not self.parser.command_type() == self.parser.L_COMMAND:
                self.current_rom_address += INSTRUCTION_SIZE_IN_WORDS
    """
    Write a single hack instruction in the output .hack file,
    add a newline after it
    """
    def _write_to_output(self, hack_instruction):
        self.output_file.write(hack_instruction + "\n")
开发者ID:adirz,项目名称:sample-projects,代码行数:80,代码来源:Assembler.py

示例9: Parser

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [as 别名]
#Author: Josh Wretlind
#Python Assignment #3
#Class: CSCI 410 - Elements of Computing Systems
#Written in: Python 2.7

import sys,string,os
from Parser import Parser

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

parse = Parser(infile)
outfilecontents = ""
while parse.hasMoreCommands():
    parse.advance()
    outfilecontents += parse.output()
    
output = open(outfile, 'w')
output.write(outfilecontents)

parse.stats()
开发者ID:joshWretlind,项目名称:CSCI410-ElementsOfComputingSystems,代码行数:23,代码来源:jacklex.py

示例10: main

# 需要导入模块: from Parser import Parser [as 别名]
# 或者: from Parser.Parser import advance [as 别名]
def main():
    # open an output file
    input_path = sys.argv[FILE_POS]
    if isdir(input_path):
        input_list = [ input_path + "/" +f for f in listdir(input_path) 
            if (isfile(join(input_path, f))) and (f.endswith(".asm")) ]
    else:
        input_list = [input_path]
    
    for input_file in input_list:
        index = input_file.index(".")
        output_file = open(input_file[:index] + ".hack", "w")
        # parse a new line
        code = Code()
        symbol_table = SymbolTable()
        counter_address = FIRST_ADDRESS_RAM
        counter_rom = FIRST_ADDRESS_ROM

        # first pass
        parser_first_pass = Parser(input_file)
        while parser_first_pass.has_more_commands():
            command = parser_first_pass.advance()
            parse_type = parser_first_pass.command_type()
            if parse_type == L_COMMAND:
                if not symbol_table.contains(command[1:-1]):
                    symbol_table.add_entry(command[1:-1], counter_rom)
            else:
               counter_rom+=1

        # second pass
        parser_second_pass = Parser(input_file)
        while parser_second_pass.has_more_commands():
            command = parser_second_pass.advance()
            line_to_hack = ""
            parse_type = parser_second_pass.command_type()

            # translate the line to an A Command
            if parse_type == A_COMMAND:
                if command[1:].isdigit():
                    address = command[1:]
                else:
                    if symbol_table.contains(command[1:]):
                        address = symbol_table.get_address(command[1:])
                    else:
                        symbol_table.add_entry(command[1:], counter_address)
                        address = counter_address
                        
                        counter_address += 1
                binary_repr = str(bin(int(address))[2:].zfill(15))
                line_to_hack = A_PREFIX + binary_repr

            # translate the line to a C Command
            if parse_type == C_COMMAND:
                # C command comp
                comp_type = parser_second_pass.comp()
                code_comp = code.comp(comp_type)
                # C command dest
                dest_type = parser_second_pass.dest()
                code_dest = code.dest(dest_type)
                # C command jump
                jump_type = parser_second_pass.jump()
                code_jump = code.jump(jump_type)
                if ("<" in comp_type) or (">" in comp_type):
                    line_to_hack = C_PREFIX_SPE + code_comp + code_dest + code_jump
                else:
                    line_to_hack = C_PREFIX_REG + code_comp + code_dest + code_jump
                
            if parse_type == L_COMMAND:
                continue

            # write the line to the output file
            output_file.write(line_to_hack + "\n")


        output_file.close()
开发者ID:hadarfranco,项目名称:From-NAND-to-Tetris,代码行数:77,代码来源:Assembler.py


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