def Goal(self): if self.lex.token in ['num', 'var', '(']: val = self.Expr() self.lex.match('\0') # expression? print(val) elif self.lex.token == 'set': # set command? self.Assign() self.lex.match('\0') else: raise SyntaxError()
def Goal(self): if self.lex.token in ['num', 'var', '(']: tree = self.Expr() self.lex.match('\0') return tree elif self.lex.token == 'set': tree = self.Assign() self.lex.match('\0') return tree else: raise SyntaxError()
def Factor(self): left = self.Term() while True: if self.lex.token in ['+', '-', '\0', ')']: return left elif self.lex.token == '*': self.lex.scan() left = TimesNode(left, self.Term()) elif self.lex.token == '/': self.lex.scan() left = DivideNode(left, self.Term()) else: raise SyntaxError()
def Expr(self): left = self.Factor() # left subtree while True: if self.lex.token in ['\0', ')']: return left elif self.lex.token == '+': self.lex.scan() left = PlusNode(left, self.Factor()) # add root-node elif self.lex.token == '-': self.lex.scan() left = MinusNode(left, self.Factor()) # grows up/right else: raise SyntaxError()
def Factor(self): left = self.Term() while True: if self.lex.token in ['+', '-', '\0', ')']: return left elif self.lex.token == '*': self.lex.scan() left = left * self.Term() elif self.lex.token == '/': self.lex.scan() left = left / self.Term() else: raise SyntaxError()
def Expr(self): left = self.Factor() while True: if self.lex.token in ['\0', ')']: return left elif self.lex.token == '+': self.lex.scan() left = left + self.Factor() elif self.lex.token == '-': self.lex.scan() left = left - self.Factor() else: raise SyntaxError()
def Expr(self): # 构造表达式? left = self.Factor() while True: if self.lex.token in ['\0', ')']: # '\0'句子结束符或者式子中的')' return left elif self.lex.token == '+': # 最后处理'+', '-' self.lex.scan() left = left + self.Factor() elif self.lex.token == '-': self.lex.scan() left = left - self.Factor() else: raise SyntaxError()
def Term(self): if self.lex.token == 'num': leaf = NumNode(self.lex.match('num')) return leaf elif self.lex.token == 'var': leaf = VarNode(self.lex.value, self.lex.start) self.lex.scan() return leaf elif self.lex.token == '(': self.lex.scan() tree = self.Expr() self.lex.match(')') return tree else: raise SyntaxError()
def Term(self): if self.lex.token == 'num': val = self.lex.match('num') # numbers return val elif self.lex.token == 'var': if self.lex.value in self.vars.keys(): # keys(): EIBTI! val = self.vars[self.lex.value] # look up name's value self.lex.scan() return val else: raise UndefinedError(self.lex.value) elif self.lex.token == '(': self.lex.scan() val = self.Expr() # sub-expression self.lex.match(')') return val else: raise SyntaxError()