1# -----------------------------------------------------------------------------
2# yacc_inf.py
3#
4# Infinite recursion
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
23def p_statement_assign(t):
24    'statement : NAME EQUALS expression'
25    names[t[1]] = t[3]
26
27def p_statement_expr(t):
28    'statement : expression'
29    print(t[1])
30
31def p_expression_binop(t):
32    '''expression : expression PLUS expression
33                  | expression MINUS expression
34                  | expression TIMES expression
35                  | expression DIVIDE expression'''
36    if t[2] == '+'  : t[0] = t[1] + t[3]
37    elif t[2] == '-': t[0] = t[1] - t[3]
38    elif t[2] == '*': t[0] = t[1] * t[3]
39    elif t[2] == '/': t[0] = t[1] / t[3]
40
41def p_expression_uminus(t):
42    'expression : MINUS expression %prec UMINUS'
43    t[0] = -t[2]
44
45def p_expression_group(t):
46    'expression : LPAREN expression RPAREN'
47    t[0] = t[2]
48
49def p_error(t):
50    print("Syntax error at '%s'" % t.value)
51
52yacc.yacc()
53
54
55
56
57