1# -----------------------------------------------------------------------------
2# yacc_badprec.py
3#
4# Bad precedence specifier
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 = "blah"
15
16# dictionary of names
17names = { }
18
19def p_statement_assign(t):
20    'statement : NAME EQUALS expression'
21    names[t[1]] = t[3]
22
23def p_statement_expr(t):
24    'statement : expression'
25    print(t[1])
26
27def p_expression_binop(t):
28    '''expression : expression PLUS expression
29                  | expression MINUS expression
30                  | expression TIMES expression
31                  | expression DIVIDE expression'''
32    if t[2] == '+'  : t[0] = t[1] + t[3]
33    elif t[2] == '-': t[0] = t[1] - t[3]
34    elif t[2] == '*': t[0] = t[1] * t[3]
35    elif t[2] == '/': t[0] = t[1] / t[3]
36
37def p_expression_uminus(t):
38    'expression : MINUS expression %prec UMINUS'
39    t[0] = -t[2]
40
41def p_expression_group(t):
42    'expression : LPAREN expression RPAREN'
43    t[0] = t[2]
44
45def p_expression_number(t):
46    'expression : NUMBER'
47    t[0] = t[1]
48
49def p_expression_name(t):
50    'expression : NAME'
51    try:
52        t[0] = names[t[1]]
53    except LookupError:
54        print("Undefined name '%s'" % t[1])
55        t[0] = 0
56
57def p_error(t):
58    print("Syntax error at '%s'" % t.value)
59
60yacc.yacc()
61
62
63
64
65