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