Example #1
0
 def 条件语句(self):
     sub_tree = TreeNode('<条件语句>')
     syntax_tree = None
     if isinstance(self.token, Keyword) and self.token.value == 'if':
         child_tree = TreeNode(self.token)
         self.token = self.lexer.forward()
         condition, ast_condition = self.条件()
         child_tree.sublings.append(condition)
         if isinstance(self.token, Keyword) and self.token.value == 'then':
             child_tree.sublings.append(TreeNode(self.token))
             self.token = self.lexer.forward()
             statment, ast_true_stmt = self.语句()
             child_tree.sublings.append(statment)
             ast_false_stmt = SyntaxTree.EmptyStatement()
             if isinstance(self.token, Keyword) and self.token.value == 'else':
                 child_tree.sublings.append(TreeNode(self.token))
                 self.token = self.lexer.forward()
                 statment, ast_false_stmt = self.语句()
                 
                 child_tree.sublings.append(statment)
             sub_tree.child = child_tree
             syntax_tree = SyntaxTree.IfStatement(ast_condition, ast_true_stmt, false_stmt=ast_false_stmt)
             return sub_tree, syntax_tree
         else:
             if self.lexer.hasnext():
                 statement = self.lexer.statement.split('\n')
                 pos_str = "{}\n{}".format(statement[self.lexer.line_index -1 ], " "*(self.lexer.character_index-2) )
                 pos_str += '^'
                 invalid_str = '"then" expected, get "{}" at line {}'.format(self.token.value, self.lexer.line_index)
                 raise SyntaxException("{}\n{}".format(invalid_str, pos_str))
             else:
                 raise SyntaxException("{}".format('unexpected EOF!'))
     else:
         self.unexpected_error('if')
Example #2
0
 def 语句(self):
     sub_tree = TreeNode('<语句>')
     if isinstance(self.token, Identifier):
         # assginment
         child_tree, syntax_tree = self.赋值语句()
         sub_tree.child = child_tree
         # syntax_tree.print()
         return sub_tree, syntax_tree
     call_tab = {
         'if':self.条件语句,
         'while':self.当型循环语句,
         'call':self.过程调用语句,
         'read':self.读语句,
         'write':self.写语句,
         'begin':self.复合语句,
         'repeat':self.重复语句,
     }
     if isinstance(self.token, Keyword) and self.token.value in call_tab:
         # print("选择 {}".format(self.token.value))
         child_tree, syntax_tree = call_tab[self.token.value]()
         sub_tree.child = child_tree
         return sub_tree, syntax_tree
     else:
         sub_tree.child = TreeNode("")
         return sub_tree, SyntaxTree.EmptyStatement()