1# -----------------------------------------------------------------------------
2# yacc_literal.py
3#
4# Grammar with bad literal characters
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','+','-'),
16    ('left','*','/'),
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 '+' expression
33                  | expression '-' expression
34                  | expression '*' expression
35                  | expression '/' expression
36                  | expression '**' expression '''
37    if 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    elif t[2] == '/': t[0] = t[1] / t[3]
41
42def p_expression_uminus(t):
43    'expression : MINUS expression %prec UMINUS'
44    t[0] = -t[2]
45
46def p_expression_group(t):
47    'expression : LPAREN expression RPAREN'
48    t[0] = t[2]
49
50def p_expression_number(t):
51    'expression : NUMBER'
52    t[0] = t[1]
53
54def p_expression_name(t):
55    'expression : NAME'
56    try:
57        t[0] = names[t[1]]
58    except LookupError:
59        print("Undefined name '%s'" % t[1])
60        t[0] = 0
61
62def p_error(t):
63    print("Syntax error at '%s'" % t.value)
64
65yacc.yacc()
66
67
68
69
70