1# ----------------------------------------------------------------------------- 2# yacc_nodoc.py 3# 4# Rule with a missing doc-string 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 = ( 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_expr(t): 28 print(t[1]) 29 30def p_expression_binop(t): 31 '''expression : expression PLUS expression 32 | expression MINUS expression 33 | expression TIMES expression 34 | expression DIVIDE expression''' 35 if t[2] == '+' : t[0] = t[1] + t[3] 36 elif t[2] == '-': t[0] = t[1] - t[3] 37 elif t[2] == '*': t[0] = t[1] * t[3] 38 elif t[2] == '/': t[0] = t[1] / t[3] 39 40def p_expression_uminus(t): 41 'expression : MINUS expression %prec UMINUS' 42 t[0] = -t[2] 43 44def p_expression_group(t): 45 'expression : LPAREN expression RPAREN' 46 t[0] = t[2] 47 48def p_expression_number(t): 49 'expression : NUMBER' 50 t[0] = t[1] 51 52def p_expression_name(t): 53 'expression : NAME' 54 try: 55 t[0] = names[t[1]] 56 except LookupError: 57 print("Undefined name '%s'" % t[1]) 58 t[0] = 0 59 60def p_error(t): 61 print("Syntax error at '%s'" % t.value) 62 63yacc.yacc() 64 65 66 67 68