blob: e7336c2f0be9bf45c2ada5d814d0928e4009bde5 [file] [log] [blame]
Steve Reinhardtba2eae52006-05-22 14:29:33 -04001# -----------------------------------------------------------------------------
2# yacc_rr.py
3#
4# A grammar with a reduce/reduce conflict
5# -----------------------------------------------------------------------------
6import sys
Steve Reinhardtba2eae52006-05-22 14:29:33 -04007
Nathan Binkerte1270f82009-08-16 13:39:58 -07008if ".." not in sys.path: sys.path.insert(0,"..")
Nathan Binkert44ebb8d2007-05-24 21:54:51 -07009import ply.yacc as yacc
10
Steve Reinhardtba2eae52006-05-22 14:29:33 -040011from 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_assign_2(t):
28 'statement : NAME EQUALS NUMBER'
29 names[t[1]] = t[3]
30
31def p_statement_expr(t):
32 'statement : expression'
Nathan Binkerte1270f82009-08-16 13:39:58 -070033 print(t[1])
Steve Reinhardtba2eae52006-05-22 14:29:33 -040034
35def p_expression_binop(t):
36 '''expression : expression PLUS expression
37 | expression MINUS expression
38 | expression TIMES expression
39 | expression DIVIDE expression'''
40 if t[2] == '+' : t[0] = t[1] + t[3]
41 elif t[2] == '-': t[0] = t[1] - t[3]
42 elif t[2] == '*': t[0] = t[1] * t[3]
Nathan Binkerte1270f82009-08-16 13:39:58 -070043 elif t[2] == '/': t[0] = t[1] / t[3]
Steve Reinhardtba2eae52006-05-22 14:29:33 -040044
45def p_expression_uminus(t):
46 'expression : MINUS expression %prec UMINUS'
47 t[0] = -t[2]
48
49def p_expression_group(t):
50 'expression : LPAREN expression RPAREN'
51 t[0] = t[2]
52
53def p_expression_number(t):
54 'expression : NUMBER'
55 t[0] = t[1]
56
57def p_expression_name(t):
58 'expression : NAME'
59 try:
60 t[0] = names[t[1]]
61 except LookupError:
Nathan Binkerte1270f82009-08-16 13:39:58 -070062 print("Undefined name '%s'" % t[1])
Steve Reinhardtba2eae52006-05-22 14:29:33 -040063 t[0] = 0
64
65def p_error(t):
Nathan Binkerte1270f82009-08-16 13:39:58 -070066 print("Syntax error at '%s'" % t.value)
Steve Reinhardtba2eae52006-05-22 14:29:33 -040067
Steve Reinhardtba2eae52006-05-22 14:29:33 -040068yacc.yacc()
69
70
71
72