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