1# -----------------------------------------------------------------------------
2# yacc_notfunc.py
3#
4# p_rule not defined as a function
5# -----------------------------------------------------------------------------
6import sys
7
8if ".." not in sys.path: sys.path.insert(0,"..")
9import ply.yacc as yacc
10
11from calclex import tokens
12
13# Parsing rules
14precedence = (
15    ('left','PLUS','MINUS'),
16    ('left','TIMES','DIVIDE'),
17    ('right','UMINUS'),
18    )
19
20# dictionary of names
21names = { }
22
23p_statement_assign = "Blah"
24
25def p_statement_expr(t):
26    'statement : expression'
27    print(t[1])
28
29def p_expression_binop(t):
30    '''expression : expression PLUS expression
31                  | expression MINUS expression
32                  | expression TIMES expression
33                  | expression DIVIDE expression'''
34    if t[2] == '+'  : t[0] = t[1] + t[3]
35    elif t[2] == '-': t[0] = t[1] - t[3]
36    elif t[2] == '*': t[0] = t[1] * t[3]
37    elif t[2] == '/': t[0] = t[1] / t[3]
38
39def p_expression_uminus(t):
40    'expression : MINUS expression %prec UMINUS'
41    t[0] = -t[2]
42
43def p_expression_group(t):
44    'expression : LPAREN expression RPAREN'
45    t[0] = t[2]
46
47def p_expression_number(t):
48    'expression : NUMBER'
49    t[0] = t[1]
50
51def p_expression_name(t):
52    'expression : NAME'
53    try:
54        t[0] = names[t[1]]
55    except LookupError:
56        print("Undefined name '%s'" % t[1])
57        t[0] = 0
58
59def p_error(t):
60    print("Syntax error at '%s'" % t.value)
61
62yacc.yacc()
63
64
65
66
67