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


Python SymbolTable.define方法代码示例

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


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

示例1: TestSymbolTable

# 需要导入模块: from SymbolTable import SymbolTable [as 别名]
# 或者: from SymbolTable.SymbolTable import define [as 别名]
class TestSymbolTable(unittest.TestCase):
  def setUp(self):
    self.symbol_table = SymbolTable()

  def tearDown(self):
    pass

  # def assertion(self, actual, expected):
  #   asserted = actual == expected
  #   if not asserted:
  #     print 'FAILED: assert {} == {}'.format(actual, expected)
  #   assert asserted

  def test_constructor(self):
    assert self.symbol_table.__class__.__name__ == 'SymbolTable'

  def test_define_var(self):
    self.symbol_table.define('foo', 'int', 'STATIC')

    assert self.symbol_table.counts['STATIC'] == 1
    assert self.symbol_table.class_scope['foo'] == ('int', 'STATIC', 0)

  def test_define_field(self):
    self.symbol_table.define('bar', 'Snake', 'VAR')
    self.symbol_table.define('foo', 'int', 'FIELD')

    assert self.symbol_table.counts['VAR'] == 1
    assert self.symbol_table.subroutine_scope['bar'] == ('Snake', 'VAR', 0)

  def test_varCount(self):
    self.symbol_table.define('foo', 'int', 'FIELD')

    assert self.symbol_table.varCount('FIELD')  == 1
    assert self.symbol_table.varCount('ARG')    == 0
    assert self.symbol_table.varCount('STATIC') == 2
    assert self.symbol_table.varCount('VAR')    == 1

  def test_kindOf(self):
    self.symbol_table.define('foo', 'int', 'FIELD')

    assert self.symbol_table.kindOf('foo') == 'FIELD'
    assert self.symbol_table.kindOf('bar') == 'NONE'

  def test_typeOf(self):
    self.symbol_table.define('foo', 'Square', 'FIELD')

    assert self.symbol_table.typeOf('foo') == 'Square'
    assert self.symbol_table.typeOf('bar') == 'NONE'

  def test_indexOf(self):
    self.symbol_table.define('foo', 'boolean', 'FIELD')
    self.symbol_table.define('bar', 'char', 'FIELD')
    self.symbol_table.define('qaz', 'char', 'STATIC')

    assert self.symbol_table.indexOf('foo') == 0
    assert self.symbol_table.indexOf('bar') == 1
    assert self.symbol_table.indexOf('qaz') == 1
    assert self.symbol_table.indexOf('quz') == 'NONE'
开发者ID:kmanzana,项目名称:nand2tetris,代码行数:60,代码来源:SymbolTable_Spec.py

示例2: __init__

# 需要导入模块: from SymbolTable import SymbolTable [as 别名]
# 或者: from SymbolTable.SymbolTable import define [as 别名]
class CompilationEngine:

    def __init__(self, inputFile, outputFile):
        self.tokenizer = JackTokenizer(inputFile)
        self.vmWriter = VMWriter(outputFile)
        self.symbolTable = SymbolTable()
        self.classname = ""
        self.CompileClass()
        self.whilecounter = 0
        self.ifcounter = 0

    def CompileClass(self):
        #classname
        self.tokenizer.advance()
        self.classname = self.tokenizer.identifier()
        self.tokenizer.advance()
        # ignore {
        self.tokenizer.advance()

        while self.tokenizer.keyWord() == "static" or self.tokenizer.keyWord() == "field":
            self.CompileClassVarDec()

        while self.tokenizer.keyWord() == "constructor" or self.tokenizer.keyWord() == "function" or self.tokenizer.keyWord() == "method":
            self.CompileSubroutine()

        #ignore }
        self.tokenizer.advance()



    def CompileClassVarDec(self):

        kind = self.tokenizer.keyWord()
        self.tokenizer.advance()
        type = self.compileType()
        name = self.tokenizer.identifier()
        self.symbolTable.define(name, type, kind)
        self.tokenizer.advance()

        # add the rest of var names, if there are
        while self.tokenizer.symbol() == ",":
            self.tokenizer.advance()
            name = self.tokenizer.identifier()
            self.symbolTable.define(name, type, kind)
            self.tokenizer.advance()

        # ignore ;
        self.tokenizer.advance()

    def CompileSubroutine(self):

        self.symbolTable.startSubroutine()
        self.ifcounter = 0
        self.whilecounter = 0
        # constructor | function | method
        functype = self.tokenizer.keyWord()
        self.tokenizer.advance()

        if functype == "method":
            self.symbolTable.define("this", self.classname, "arg")

        self.tokenizer.advance()

        subrotineName = self.classname + "." + self.tokenizer.identifier()
        self.tokenizer.advance()

        # ( parameterList )
        self.tokenizer.advance()
        self.compileParameterList()
        self.tokenizer.advance()

        # subrotineBody
        # ignore {
        self.tokenizer.advance()
        # varDec*
        while self.tokenizer.keyWord() == "var":
            self.compileVarDec()

        self.vmWriter.writeFunction(subrotineName, self.symbolTable.varCount("var"))
        # allocate memory for constructor
        # if functype == "constructor":
        #     self.vmWriter.writePush("constant" , self.symbolTable.varCount("field"))
        #     self.vmWriter.writeCall("Memory.alloc", "1")

        if functype == "constructor" or functype == "method":
            if functype == "constructor":
                self.vmWriter.writePush("constant" , self.symbolTable.varCount("field"))
                self.vmWriter.writeCall("Memory.alloc", "1")
            else:
                self.vmWriter.writePush("argument", "0")
            self.vmWriter.writePop("pointer", "0")


        # statements
        self.compileStatements()

        # ignore }
        self.tokenizer.advance()

    def compileParameterList(self):
#.........这里部分代码省略.........
开发者ID:idan0610,项目名称:nand-project11,代码行数:103,代码来源:CompilationEngine.py

示例3: __init__

# 需要导入模块: from SymbolTable import SymbolTable [as 别名]
# 或者: from SymbolTable.SymbolTable import define [as 别名]
class CompilationEngine:

    keywordConsts = ["null", "true", "false", "this"] 
    def __init__(self, tokenizer, outputFile, vmFile):
        from SymbolTable import SymbolTable
        from VMWriter import VMWriter
        self.tokenizer = tokenizer
        self.outputFile = outputFile
        self.symbolTable = SymbolTable()
        self.vmWriter = VMWriter(vmFile)
        self.labelNum = 0
        print(outputFile)
    
    def compileClass(self):
        from JackTokenizer import JackTokenizer
        self.indentLevel = 0
        NUM_OPENING_STATEMENTS = 3
        classVarOpenings = ['static', 'field']
        subOpenings = ['constructor', 'function', 'method']

        if self.tokenizer.currentToken != "class":
            raise Exception("Keyword 'class' expected")
        self.writeFormatted("<class>")
        self.indentLevel += 1
        self.printToken() #Should print 'class'
        if self.tokenizer.hasMoreTokens():
            self.tokenizer.advance()
            self.printToken() #Should print class name
            self.className = self.tokenizer.identifier()
            self.writeClassOrSubInfo("class", False)

        if self.tokenizer.hasMoreTokens():
            self.tokenizer.advance()
            self.printToken() #Should print '{'
        
        if self.tokenizer.hasMoreTokens():
            self.tokenizer.advance()
        
        self.fieldCount = 0
        while self.tokenizer.hasMoreTokens() and self.tokenizer.keyWord() in classVarOpenings:
            if self.tokenizer.keyWord() == "field":
                self.fieldCount += 1
            self.compileClassVarDec()
        while(self.tokenizer.hasMoreTokens() and self.tokenizer.tokenType == JackTokenizer.KEYWORD 
                and self.tokenizer.keyWord() in subOpenings):
            self.compileSubroutine()
        self.printToken()
        self.writeFormatted("</class>")
        self.indentLevel -= 1
    
    def compileClassVarDec(self):
        from JackTokenizer import JackTokenizer
        from SymbolTable import SymbolTable 
        self.writeFormatted("<classVarDec>")
        self.indentLevel += 1
        self.printToken() #Should print static or field
        if self.tokenizer.tokenType == JackTokenizer.KEYWORD:
            if self.tokenizer.keyWord() == "static":
                kind = SymbolTable.STATIC
            elif self.tokenizer.keyWord() == "field":
                kind = SymbolTable.FIELD
            else:
                raise Exception("Invalid kind of class variable " + self.tokenizer.keyWord())
        else:
            raise Exception("Keyword expected")
        
        if self.tokenizer.hasMoreTokens():
            self.tokenizer.advance()
            self.printToken() #Should print the variable type
            identifierType = self.tokenizer.currentToken
            isKeyword = self.tokenizer.tokenType == JackTokenizer.KEYWORD

        if not isKeyword:
            self.writeClassOrSubInfo("class", True)

        varNames = []
        if self.tokenizer.hasMoreTokens():
            self.tokenizer.advance()
            self.printToken() #Should print variable name
            varNames.append(self.tokenizer.currentToken)
            if self.tokenizer.hasMoreTokens(): 
                self.tokenizer.advance()

        while self.tokenizer.symbol() != ";" and self.tokenizer.hasMoreTokens():
            if self.tokenizer.symbol() != ",":
                raise Exception("Invalid variable list")
            self.printToken() #Should print ','
            self.tokenizer.advance()
            self.printToken() #Should print variable name
            varNames.append(self.tokenizer.currentToken)
            if kind == SymbolTable.FIELD:
                self.fieldCount += 1
            if not self.tokenizer.hasMoreTokens():
                raise Exception("More tokens expected")
            self.tokenizer.advance()
        self.printToken()
    

        for name in varNames:
            self.symbolTable.define(name, identifierType, kind)
#.........这里部分代码省略.........
开发者ID:itzhak-razi,项目名称:Elements-of-Computing-Systems-Assignments,代码行数:103,代码来源:CompilationEngine.py

示例4: __init__

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

#.........这里部分代码省略.........
        while self.tokenizer.getToken() == 'var':
            self.compileDec()
        numOfVars = self.classTable.varCount(Toolbox.VAR)

        if subroutineType == 'function':
            self.writer.writeFunction(self.className + "." + name, numOfVars)
        elif subroutineType == 'constructor':
            self.writer.writeFunction(self.className + "." + name, numOfVars)
            # push constant (num of fields)
            # call Memory.alloc 1
            # pop pointer 0
            fields = self.classTable.varCount(Toolbox.FIELD)
            self.writer.writePush(Toolbox.CONST, fields)
            self.writer.writeCall('Memory.alloc', 1)
            self.writer.writePop(Toolbox.POINTER, 0)
        else:  # method
            self.writer.writeFunction(self.className + "." + name, numOfVars)
            # push argument 0
            # pop pointer 0
            self.writer.writePush(Toolbox.SEG_ARG, 0)
            self.writer.writePop(Toolbox.POINTER, 0)

        # statements
        self.compileStatements()
        # }
        self.getNext()

    def compileParameterList(self, method=False):
        """Compiles a (possibly empty) parameter list,
        not including the enclosing "()"."""
        tokenType, name = '', ''

        if method:  # Add this to method's var list.
            self.classTable.define(None, None, Toolbox.ARG)

        if self.tokenizer.tokenType() != self.tokenizer.SYMBOL:  # param list not empty
            while True:
                tokenType = self.tokenizer.getToken()
                self.getNext()

                name = self.tokenizer.getToken()
                self.classTable.define(name, tokenType, Toolbox.ARG)
                self.getNext()

                if self.tokenizer.getToken() == ')':
                    break

                self.getNext()  # ','

    def compileStatements(self):  # (letStatement | ifStatement | whileStatement | doStatement | returnStatement)*
        """Compiles a sequence of statements,
        not including the enclosing "{}"."""
        token = self.tokenizer.getToken()
        while token in ["let", "if", "while", "do", "return"]:
            if token == 'let':
                self.compileLet()
            elif token == 'if':
                self.compileIf()
            elif token == 'while':
                self.compileWhile()
            elif token == 'do':
                self.compileDo()
            elif token == 'return':
                self.compileReturn()
            token = self.tokenizer.getToken()
开发者ID:nonocodebox,项目名称:from-nand-to-tetris,代码行数:69,代码来源:CompilationEngine.py

示例5: __init__

# 需要导入模块: from SymbolTable import SymbolTable [as 别名]
# 或者: from SymbolTable.SymbolTable import define [as 别名]
class CompilationEngine:

    def __init__(self, input_file, output_file):
        self.jack_tokenizer = JackTokenizer(input_file)
        self.symbol_table = SymbolTable()
        self.writer = VMWriter(output_file)
        self.class_name = ""
        self.subroutine_name = ""
        self.return_type = ""
        self.label_counter_if = 0
        self.label_counter_while = 0
        self.num_args_called_function = 0
        self.is_unary = False
        self.dic_arithmetic = {"+" : "add" , "-" : "sub", "*" : "call Math.multiply 2",
                               "/" : "call Math.divide 2", "&" : "and", "|" : "or", "<" : "lt", ">" : "gt", "=" : "eq"}

    def compile_class(self):
        # "class className {
        for i in range(NUM_TOKENS_CLASS_DEC):
            self.jack_tokenizer.has_more_tokens()
            self.jack_tokenizer.advance()
            # saves the className
            if self.jack_tokenizer.token_type() == IDENTIFIER:
                self.class_name = self.jack_tokenizer.identifier()
        # classVarDec* or SubroutineDec*
        while self.jack_tokenizer.has_more_tokens():
            self.jack_tokenizer.advance()
            token_type = self.jack_tokenizer.token_type()
            if token_type == KEYWORD and (self.jack_tokenizer.key_word() == "static" or
                                                  self.jack_tokenizer.key_word() == "field"):
                self.compile_class_var_dec()
            if token_type == KEYWORD and (self.jack_tokenizer.key_word() == "function" or
                                                  self.jack_tokenizer.key_word() == "method" or
                                                  self.jack_tokenizer.key_word() == "constructor"):
                self.compile_subroutine()
            if token_type == SYMBOL and self.jack_tokenizer.symbol() == "}":
                break

    def compile_class_var_dec(self):
        # "static" of "field"
        kind = self.jack_tokenizer.key_word()
        self.jack_tokenizer.has_more_tokens()
        self.jack_tokenizer.advance()
        # type
        if self.jack_tokenizer.token_type() == KEYWORD:
            type = self.jack_tokenizer.key_word()
        else:
            type = self.jack_tokenizer.identifier()
        while self.jack_tokenizer.has_more_tokens():
            self.jack_tokenizer.advance()
            token_type = self.jack_tokenizer.token_type()
            if token_type == IDENTIFIER:
                name = self.jack_tokenizer.identifier()
                self.symbol_table.define(name,type,kind)
            elif token_type == SYMBOL:
                if self.jack_tokenizer.symbol() == ";":
                    break


    def compile_subroutine(self):
        self.symbol_table.start_subroutine()
        self.subroutine_name = ""
        self.return_type = ""
        self.label_counter_if = 0
        self.label_counter_while = 0
        #  the curr token : "constructor" or "function" or "method
        type_of_subroutine = self.jack_tokenizer.key_word()
        self.jack_tokenizer.has_more_tokens()
        self.jack_tokenizer.advance()
        # the curr token : return type of the subroutine
        if self.jack_tokenizer.token_type() == KEYWORD:
            self.return_type = self.jack_tokenizer.key_word()
        else:
            self.return_type = self.jack_tokenizer.identifier()
        self.jack_tokenizer.has_more_tokens()
        self.jack_tokenizer.advance()
        self.subroutine_name = self.jack_tokenizer.identifier()
        while self.jack_tokenizer.has_more_tokens():
            self.jack_tokenizer.advance()
            if self.jack_tokenizer.symbol() == "(":
                if type_of_subroutine == "method":
                    self.symbol_table.define(THIS, self.class_name, ARG)
                self.compile_parameter_list()
                # the curr token should be -  ")"
            if self.jack_tokenizer.symbol() == '{':
                while self.jack_tokenizer.has_more_tokens():
                    self.jack_tokenizer.advance()
                    token_type = self.jack_tokenizer.token_type()
                    if token_type == KEYWORD:
                        if self.jack_tokenizer.key_word() == "var":
                            self.compile_var_dec()
                            continue
                        else:
                            self.writer.write_function(self.class_name +
                                                       "." + self.subroutine_name, self.symbol_table.var_count(VAR))
                            if type_of_subroutine == "constructor":
                                self.writer.write_push(CONST, self.symbol_table.var_count(FIELD))
                                self.writer.write_call("Memory.alloc", 1)
                                self.writer.write_pop("pointer", 0)
                            elif type_of_subroutine == "method":
#.........这里部分代码省略.........
开发者ID:hadarfranco,项目名称:From-NAND-to-Tetris,代码行数:103,代码来源:CompilationEngine.py

示例6: __init__

# 需要导入模块: from SymbolTable import SymbolTable [as 别名]
# 或者: from SymbolTable.SymbolTable import define [as 别名]
class CompilationEngine:
  CONVERT_KIND = {
    'ARG': 'ARG',
    'STATIC': 'STATIC',
    'VAR': 'LOCAL',
    'FIELD': 'THIS'
  }

  ARITHMETIC = {
    '+': 'ADD',
    '-': 'SUB',
    '=': 'EQ',
    '>': 'GT',
    '<': 'LT',
    '&': 'AND',
    '|': 'OR'
  }

  ARITHMETIC_UNARY = {
    '-': 'NEG',
    '~': 'NOT'
  }

  if_index    = -1
  while_index = -1

  def __init__(self, vm_writer, tokenizer):
    self.vm_writer    = vm_writer
    self.tokenizer    = tokenizer
    self.symbol_table = SymbolTable()
    self.buffer       = []

  # 'class' className '{' classVarDec* subroutineDec* '}'
  def compileClass(self):
    self.get_token() # 'class'
    self.class_name = self.get_token() # className
    self.get_token() # '{'

    while self.is_class_var_dec():
      self.compileClassVarDec() # classVarDec*

    while self.is_subroutine_dec():
      self.compileSubroutine() # subroutineDec*

    self.vm_writer.close()

  # ('static' | 'field' ) type varName (',' varName)* ';'
  def compileClassVarDec(self):
    kind = self.get_token() # ('static' | 'field' )
    type = self.get_token() # type
    name = self.get_token() # varName

    self.symbol_table.define(name, type, kind.upper())

    while self.peek() != ';': # (',' varName)*
      self.get_token() # ','
      name = self.get_token() # varName
      self.symbol_table.define(name, type, kind.upper())

    self.get_token() # ';'

  # subroutineDec: ('constructor' | 'function' | 'method') ('void' | type) subroutineName '(' parameterList ')' subroutineBody
  # subroutineBody: '{' varDec* statements '}'
  def compileSubroutine(self):
    subroutine_kind = self.get_token() # ('constructor' | 'function' | 'method')
    self.get_token()                    # ('void' | type)
    subroutine_name = self.get_token()  # subroutineName
    self.symbol_table.startSubroutine()

    if subroutine_kind == 'method':
      self.symbol_table.define('instance', self.class_name, 'ARG')

    self.get_token() # '('
    self.compileParameterList()   # parameterList
    self.get_token() # ')'
    self.get_token() # '{'

    while 'var' == self.peek():
      self.compileVarDec() # varDec*

    function_name = '{}.{}'.format(self.class_name, subroutine_name)
    num_locals = self.symbol_table.varCount('VAR')
    self.vm_writer.writeFunction(function_name, num_locals)

    if subroutine_kind == 'constructor':
      num_fields = self.symbol_table.varCount('FIELD')
      self.vm_writer.writePush('CONST', num_fields)
      self.vm_writer.writeCall('Memory.alloc', 1)
      self.vm_writer.writePop('POINTER', 0)
    elif subroutine_kind == 'method':
      self.vm_writer.writePush('ARG', 0)
      self.vm_writer.writePop('POINTER', 0)

    self.compileStatements() # statements
    self.get_token() # '}'

  # ( (type varName) (',' type varName)*)?
  def compileParameterList(self):
    if ')' != self.peek():
      type = self.get_token() # type
#.........这里部分代码省略.........
开发者ID:kmanzana,项目名称:nand2tetris,代码行数:103,代码来源:CompilationEngine.py

示例7: CompliationEngine

# 需要导入模块: from SymbolTable import SymbolTable [as 别名]
# 或者: from SymbolTable.SymbolTable import define [as 别名]
class CompliationEngine(object):
    """
    Effects the actual compilation output. Gets its input from a
    JackTokenizer and emits its parsed structure into an output file/stream
    """

    MAP = {"<": "&lt;", ">": "&gt;", '"': "&quot;", "&": "&amp;"}

    def __init__(self, tokenizer, out_file_name):
        """
        Constructor
        """
        self._tokenizer = tokenizer
        self._vm_writer = VMWriter(out_file_name)
        self._class_name = None
        self._symbol_table = SymbolTable()
        self._counter = 0
        self._subroutine_name = None

    def Compile(self):
        token = str(self._tokenizer.next_token())
        if token == "class":
            self.CompileClass(token)

    def CompileClass(self, token):
        """
        takes 'class' as token
        and end the compilation
        """
        self._class_name = self._tokenizer.next_token()  # got the class name
        str(self._tokenizer.next_token())  # '{'
        token = self._tokenizer.next_token()  # field declarations

        # For declaring Class Level Variable

        while token in ["field", "static"]:
            token = self.CompileClassVarDec(token)

        # Class Methods
        while token in ["function", "method", "constructor"]:
            token = self.CompileSubroutine(token)

        self._vm_writer.writer_close()
        self._symbol_table.printSymbolTables()

    def CompileSubroutine(self, token):
        """
        Takes any among 'function', 'method', 'constructor'
        and return token after end of subroutine '}' 
        or simple next subroutine token
        """
        function_modifier = token

        str(self._tokenizer.next_token())  # return type
        function_name = str(self._tokenizer.next_token())  # name of function

        self._subroutine_name = function_name

        self._symbol_table.startSubRoutine(function_name)
        if function_modifier == "method":
            self._symbol_table.define(["this", self._class_name, "argument"])

        str(self._tokenizer.next_token())  # '('

        token = str(self._tokenizer.next_token())  # 'arguments'

        while token != ")":
            token = self.CompileParamList(token)

        str(self._tokenizer.next_token())  # '{'
        token = str(self._tokenizer.next_token())  # Statements or '}'

        while token == "var":
            token = self.CompileVarDec(token)

        local_variables = self._symbol_table.varCount("local")

        # Writing Function VM
        self._vm_writer.write_subroutine(self._class_name, function_name, local_variables)
        if function_name == "new":
            no_of_fields = self._symbol_table.varCount("field")
            self._vm_writer.write_push("constant", no_of_fields)
            self._vm_writer.write_call("Memory", "alloc", 1)
            self._vm_writer.write_pop("pointer", 0)
        if function_modifier == "method":
            self._vm_writer.write_push("argument", 0)
            self._vm_writer.write_pop("pointer", 0)
        """temp_buffer = ""
        while local_variables > 0:
            temp_buffer += 'push constant 0\n'
            local_variables -= 1
        
        self._out_file_object.write(temp_buffer)
        self._out_file_object.flush()"""

        while token != "}":
            token = self.CompileStatements(token)

        token = str(self._tokenizer.next_token())  # next subroutine
        return token
#.........这里部分代码省略.........
开发者ID:saikumarm4,项目名称:Nand2Tetris,代码行数:103,代码来源:Compilation.py

示例8: Parser

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

#.........这里部分代码省略.........
        '/':"divide",
        '&':"and",
        '|':"or",
        '<':"lt",
        '>':"gt",
        '=':"eq"
        }
        while(self.lookChild().value in writeTerms):
            op=self.createChild().value
            self.term()
            if(op in ["*","/"]):
                self.vmwriter.writeCall("Math."+writeTerms[op],2)
            else:
                self.vmwriter.writeArithmetic(writeTerms[op])

    def term(self):
        if self.lookChild().type == "integerConstant":
            self.vmwriter.writePush("constant",self.createChild().value)
        elif self.lookChild().type == "stringConstant":
            stringVal=self.createChild().value
            self.vmwriter.writePush("constant",len(stringVal))
            self.vmwriter.writeCall("String.new",1)
            for i in stringVal:
                self.vmwriter.writePush("constant",ord(i))
                self.vmwriter.writeCall("String.appendChar",2)
        elif self.lookChild().type == "keyword":
            keyword=self.createChild().value
            if keyword == 'true':
                self.vmwriter.writePush("constant",0)
                self.vmwriter.writeArithmetic("not")
            elif keyword == 'false':
                self.vmwriter.writePush("constant",0)
            elif keyword == 'null':
                self.vmwriter.writePush("constant",0)
            elif keyword == 'this':
                self.vmwriter.writePush("pointer",0)
        elif self.lookChild().value == "~":
            self.createChild()
            self.term()
            self.vmwriter.writeArithmetic("not")
        elif self.lookChild().value == "-":
            self.createChild()
            self.term()
            self.vmwriter.writeArithmetic("neg")
        elif self.lookChild().value == "(":
            self.createChild() #(
            self.expression()
            self.createChild() #)
            pass
        else: #identifier
            if self.tokens[self.index+1].value == "[":
                getItem=self.symTable.getItem(self.createChild().value)
                self.createChild() #[
                self.expression() #expression
                self.createChild() #]
                self.vmwriter.writePush(self.tranKind(getItem.kind),getItem.index)
                self.vmwriter.writeArithmetic("add")
                self.vmwriter.writePop("pointer",1)
                self.vmwriter.writePush("that",0)
            else:
                if self.tokens[self.index+1].value in [".","("]: #Subroutine call
                    self.subRoutineCall()
                else:
                    currTerm=self.symTable.getItem(self.createChild().value)
                    self.vmwriter.writePush(self.tranKind(currTerm.kind),currTerm.index)

    def expressionList(self):
        numExpr=0
        if self.lookChild().value == ")":
            return numExpr
        self.expression()
        numExpr+=1
        while self.lookChild().value==",":
            self.createChild()
            self.expression()
            numExpr+=1
        return numExpr

    def symDef(self,varType,varKind,varName):
        self.symTable.define(varType,varKind,varName)

    def tranKind(self, kind):
         if kind == "static":
            return "static"
         elif kind == "field":
            return "this"
         elif kind == "var":
            return "local"
         elif kind == "arg":
            return "argument"

    def toXML(self,fileName):
        outFile = minidom.parseString(ElementTree.tostring(self.XML)).toprettyxml()
        fileName=fileName.split(".")[0]
        try:#Safely open output file
            outFi = open(fileName+".xml","w+")
            outFi.write(outFile)
            outFi.close()
        except:
            sys.exit("There was an error opening "+fileName+".xml")
开发者ID:hubbazoot,项目名称:ecs10,代码行数:104,代码来源:Parser.py

示例9: CompilationEngine

# 需要导入模块: from SymbolTable import SymbolTable [as 别名]
# 或者: from SymbolTable.SymbolTable import define [as 别名]
class CompilationEngine(object):
	def __init__(self, src, output):
		self.tokenizer = JackTokenizer(src)
		self.writer = VMWriter(output)
		self.symbolTable = SymbolTable()
		self.labelIndex = 0

	def _acceptNextToken(self, token):
		if self.tokenizer.hasMoreToken():
			self.tokenizer.advance()
			typ = self.tokenizer.tokenType()
			tok = self.tokenizer.tokenValue()
			if type(token) != list:
				token = [token]
			if typ in token or tok in token:
				return tok
		raise SyntaxError('Parse Error')

	def _tryNextToken(self, token):
		if self.tokenizer.hasMoreToken():
			typ, tok = self.tokenizer.next()
			if type(token) != list:
				token = [token]
			if typ in token or tok in token:
				return True
		return False

	def compileClass(self):
		#'class' className '{' classVarDec* subroutineDec* '}'
		self._acceptNextToken('class')
		self.classname = self._acceptNextToken('identifier')
		self._acceptNextToken('{')

		while self._tryNextToken(['static', 'field']):
			self.compileClassVarDec()
		while self._tryNextToken(['constructor', 'function', 'method']):
			self.compileSubroutine()
		self._acceptNextToken('}')

		self.writer.close()

	def compileClassVarDec(self):
		#('static'|'field') type varName (','varName)* ';'
		kind = self._acceptNextToken(['static', 'field'])
		type = self._acceptNextToken(['int', 'char', 'boolean', 'identifier'])
		self.symbolTable.define(self._acceptNextToken('identifier'), type, kind)

		while self._tryNextToken(','):
			self._acceptNextToken(',')
			self.symbolTable.define(self._acceptNextToken('identifier'), type, kind)
		self._acceptNextToken(';')

	def compileSubroutine(self):
		#('constructor'|'function'|'method')
		#('void'|type)subroutineName'('parameterList')'
		#subroutineBody
		self.labelIndex = 0

		self.symbolTable.startSubroutine()
		subroutine = self._acceptNextToken(['constructor', 'function', 'method'])
		self._acceptNextToken(['void', 'int', 'char', 'boolean', 'identifier'])
		functionname = self._acceptNextToken('identifier')

		if subroutine == 'method':
			self.symbolTable.define('this', self.classname, 'argument')

		self._acceptNextToken('(')
		self.compileParameterList()
		self._acceptNextToken(')')
		self._acceptNextToken('{')

		argc = 0
		while self._tryNextToken('var'):
			argc += self.compileVarDec()
		self.writer.writeFunction(self.classname + '.' + functionname, argc)

		if subroutine == 'constructor':
			self.writer.writePush('constant', self.symbolTable.varCount('field'))
			self.writer.writeCall('Memory.alloc', 1)
			self.writer.writePop('pointer', 0)
		elif subroutine == 'method':
			self.writer.writePush('argument', 0)
			self.writer.writePop('pointer', 0)
		while self._tryNextToken(STATEMENT):
			self.compileStatements()
		self._acceptNextToken('}')

	def compileParameterList(self):
		#((type varName)(','type varName)*)?
		if self._tryNextToken(TYPE):
			type = self._acceptNextToken(TYPE)
			self.symbolTable.define(self._acceptNextToken('identifier'), type, 'argument')
			while self._tryNextToken(','):
				self._acceptNextToken(',')
				type = self._acceptNextToken(TYPE)
				self.symbolTable.define(self._acceptNextToken('identifier'), type, 'argument')

	def compileVarDec(self):
		#'var' type varName (',' varName)*';'
		argc = 1
#.........这里部分代码省略.........
开发者ID:TaoZang,项目名称:FromNandToTetris,代码行数:103,代码来源:CompilationEngine.py


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