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