1# -----------------------------------------------------------------------------
2# yacc_badid.py
3#
4# Attempt to define a rule with a bad-identifier name
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_statement_expr2(t):
32    'statement : bad&rule'
33    pass
34
35def p_badrule(t):
36    'bad&rule : expression'
37    pass
38
39
40def p_expression_binop(t):
41    '''expression : expression PLUS expression
42                  | expression MINUS expression
43                  | expression TIMES expression
44                  | expression DIVIDE expression'''
45    if t[2] == '+'  : t[0] = t[1] + t[3]
46    elif t[2] == '-': t[0] = t[1] - t[3]
47    elif t[2] == '*': t[0] = t[1] * t[3]
48    elif t[2] == '/': t[0] = t[1] / t[3]
49
50def p_expression_uminus(t):
51    'expression : MINUS expression %prec UMINUS'
52    t[0] = -t[2]
53
54def p_expression_group(t):
55    'expression : LPAREN expression RPAREN'
56    t[0] = t[2]
57
58def p_expression_number(t):
59    'expression : NUMBER'
60    t[0] = t[1]
61
62def p_expression_name(t):
63    'expression : NAME'
64    try:
65        t[0] = names[t[1]]
66    except LookupError:
67        print("Undefined name '%s'" % t[1])
68        t[0] = 0
69
70def p_error(t):
71    pass
72
73yacc.yacc()
74
75
76
77
78