############### # lexer stuff # ############### tokens = ('NUM', 'LPAREN', 'RPAREN', 'PLUS', 'STAR') def t_NUM(t): r'\d+' t.value = int(t.value) return t t_LPAREN = r'\(' t_RPAREN = r'\)' t_PLUS = r'\+' t_STAR = r'\*' t_ignore = ' ' def t_error(t): pass import ply.lex as lex lexer = lex.lex() ################ # parser stuff # ################ def p_exp(p): '''exp : plus_exp | term''' p[0] = p[1] def p_plus_exp(p): '''plus_exp : exp PLUS term''' p[0] = p[1] + p[3] def p_term(p): '''term : star_term | factor''' p[0] = p[1] def p_star_term(p): '''star_term : term STAR factor''' p[0] = p[1] * p[3] def p_factor(p): '''factor : paren_exp | NUM''' p[0] = p[1] def p_paren_exp(p): '''paren_exp : LPAREN exp RPAREN''' p[0] = p[2] def p_error(p): pass import ply.yacc as yacc parser = yacc.yacc() ######## # main # ######## import sys print parser.parse(sys.argv[1])