yacc_badprec2.py revision 4479
12SN/A# -----------------------------------------------------------------------------
21762SN/A# yacc_badprec2.py
32SN/A#
42SN/A# Bad precedence
52SN/A# -----------------------------------------------------------------------------
62SN/Aimport sys
72SN/Asys.tracebacklimit = 0
82SN/A
92SN/Asys.path.insert(0,"..")
102SN/Aimport ply.yacc as yacc
112SN/A
122SN/Afrom calclex import tokens
132SN/A
142SN/A# Parsing rules
152SN/Aprecedence = (
162SN/A    42,
172SN/A    ('left','TIMES','DIVIDE'),
182SN/A    ('right','UMINUS'),
192SN/A    )
202SN/A
212SN/A# dictionary of names
222SN/Anames = { }
232SN/A
242SN/Adef p_statement_assign(t):
252SN/A    'statement : NAME EQUALS expression'
262SN/A    names[t[1]] = t[3]
272665Ssaidi@eecs.umich.edu
282665Ssaidi@eecs.umich.edudef p_statement_expr(t):
292665Ssaidi@eecs.umich.edu    'statement : expression'
302SN/A    print t[1]
312SN/A
322439SN/Adef p_expression_binop(t):
332090SN/A    '''expression : expression PLUS expression
342680Sktlim@umich.edu                  | expression MINUS expression
352222SN/A                  | expression TIMES expression
362SN/A                  | expression DIVIDE expression'''
372201SN/A    if t[2] == '+'  : t[0] = t[1] + t[3]
382680Sktlim@umich.edu    elif t[2] == '-': t[0] = t[1] - t[3]
392201SN/A    elif t[2] == '*': t[0] = t[1] * t[3]
403363Sstever@eecs.umich.edu    elif t[3] == '/': t[0] = t[1] / t[3]
412201SN/A
422222SN/Adef p_expression_uminus(t):
432680Sktlim@umich.edu    'expression : MINUS expression %prec UMINUS'
442222SN/A    t[0] = -t[2]
452680Sktlim@umich.edu
462680Sktlim@umich.edudef p_expression_group(t):
472222SN/A    'expression : LPAREN expression RPAREN'
482680Sktlim@umich.edu    t[0] = t[2]
492222SN/A
502201SN/Adef p_expression_number(t):
512612SN/A    'expression : NUMBER'
522680Sktlim@umich.edu    t[0] = t[1]
532612SN/A
542612SN/Adef p_expression_name(t):
552612SN/A    'expression : NAME'
56    try:
57        t[0] = names[t[1]]
58    except LookupError:
59        print "Undefined name '%s'" % t[1]
60        t[0] = 0
61
62def p_error(t):
63    print "Syntax error at '%s'" % t.value
64
65yacc.yacc()
66
67
68
69
70