def 表达式(self): sub_tree = TreeNode('<表达式>') child_tree = None heading_operator = None syntax_tree = None if isinstance(self.token, Operator) and self.token.value in ['+', '-']: # TODO child_tree = TreeNode(self.token) heading_operator = self.token.value self.token = self.lexer.forward() anal_term, ast_term = self.项() if child_tree is not None: child_tree.sublings.append(anal_term) else: child_tree = anal_term if heading_operator is None or heading_operator in ['+']: syntax_tree = ast_term else: ast_heading_zero = TreeNode(Int(0)) syntax_tree = SyntaxTree.BinaryExpression(heading_operator, ast_heading_zero, ast_term) while isinstance(self.token, Operator) and self.token.value in ['+', '-']: anal_add, ast_add = self.加法运算符() child_tree.sublings.append(anal_add) anal_term, rhs_term = self.项() syntax_tree = SyntaxTree.BinaryExpression(ast_add, syntax_tree, rhs_term) child_tree.sublings.append(anal_term) else: sub_tree.child = child_tree return sub_tree, syntax_tree
def 项(self): sub_tree = TreeNode('<项>') child_tree, ast_tree = self.因子() while isinstance(self.token, Operator) and self.token.value in ['*', '/']: anal_mul, ast_mul = self.乘法运算符() child_tree.sublings.append(anal_mul) fractor, ast_fractor = self.因子() ast_tree = SyntaxTree.BinaryExpression(ast_mul, ast_tree, ast_fractor) child_tree.sublings.append(fractor) else: sub_tree.child = child_tree return sub_tree, ast_tree
def 条件(self): sub_tree = TreeNode('<条件>') syntax_tree = None if isinstance(self.token, Keyword) and self.token.value == 'odd': child_tree = TreeNode(self.token) self.token = self.lexer.forward() expression, ast_expression = self.表达式() syntax_tree = SyntaxTree.OddStatement(ast_expression) else: expression, ast_lhs = self.表达式() child_tree = expression operator, ast_operator = self.关系运算符() child_tree.sublings.append(operator) expression, ast_rhs = self.表达式() syntax_tree = SyntaxTree.BinaryExpression(ast_operator, ast_lhs, ast_rhs) child_tree.sublings.append(expression) sub_tree.child = child_tree return sub_tree, syntax_tree