Ejemplo n.º 1
0
    def test_exprs(self):

        # Build up some AST trees to use in tetsting
        test_factor_to_integer1 = AST('single', [GenericToken('INTEGER', '1')])
        test_factor_to_integer2 = AST('single', [GenericToken('INTEGER', '2')])
        test_factor_to_integer3 = AST('single', [GenericToken('INTEGER', '3')])

        test_term_to_factor1 = AST('single', [test_factor_to_integer1])
        test_term_to_factor2 = AST('single', [test_factor_to_integer2])

        test_expr_to_term1 = AST('single', [test_term_to_factor1])

        test_expr3 = AST('add', [test_expr_to_term1, test_term_to_factor2])

        test_term6 = AST('multiply', [test_term_to_factor2, test_factor_to_integer3])
        test_expr7 = AST('add', [test_expr_to_term1, test_term6])

        # import sys
        # parser = ExprParser(coverage_path=sys.stdout)
        # parser = ExprParser(coverage_path="/tmp/spark-grammar.cover")
        parser = ExprParser()

        (lhs, rhs, tokens,
         right_recursive, dup_rhs) = parser.check_sets()
        self.assertEqual(len(lhs), 0)
        self.assertEqual(len(rhs), 0)
        self.assertEqual(len(right_recursive), 0)

        for data, expect in [
                ['1', test_expr_to_term1],
                ['1+2', test_expr3],
                ['1+2*3', test_expr7]]:
            # print(data)
            tokens = scan_expression(data)
            # print(tokens)
            tree = parser.parse(tokens)

            # from trepan.api import debug; debug()
            self.assertEqual(tree, expect)
            pass
        return
Ejemplo n.º 2
0
 def p_factor2integer(self, args):
     ' factor ::= INTEGER '
     return AST('single', [args[0]])
Ejemplo n.º 3
0
 def p_term2factor(self, args):
     ' term ::= factor '
     return AST('single', [args[0]])
Ejemplo n.º 4
0
 def p_term_mult_factor(self, args):
     ' term ::= term MULT_OP factor '
     return AST('multiply', [args[0], args[2]])
Ejemplo n.º 5
0
 def p_expr2term(self, args):
     ' expr ::= term '
     return AST('single', [args[0]])
Ejemplo n.º 6
0
 def p_expr_add_term(self, args):
     ' expr ::= expr ADD_OP term '
     return AST('add', [args[0], args[2]])
Ejemplo n.º 7
0
 def p_expr_add_term(self, args):
     ' expr ::= expr ADD_OP term '
     op = 'add' if args[1].attr == '+' else 'subtract'
     return AST(op, [args[0], args[2]])
Ejemplo n.º 8
0
 def p_term_mult_factor(self, args):
     ' term ::= term MULT_OP factor '
     op = 'multiply' if args[1].attr == '*' else 'divide'
     return AST(op, [args[0], args[2]])
Ejemplo n.º 9
0
 def p_expr2paren(self, args):
     """ expr ::= LPAREN expr RPAREN """
     return AST('single', [args[1]])
Ejemplo n.º 10
0
 def p_expr2integer(self, args):
     """ expr ::= INTEGER """
     return AST('single', [args[0]])
Ejemplo n.º 11
0
 def p_term_mult_factor(self, args):
     """ expr ::= expr MULT_OP expr """
     op = 'multiply' if args[1].attr == '*' else 'divide'
     return AST(op, [args[0], args[2]])