1
# -----------------------------------------------------------------------------
4
# A calculator parser that makes use of closures. The function make_calculator()
5
# returns a function that accepts an input string and returns a result. All
6
# lexing rules, parsing rules, and internal state are held inside the function.
7
# -----------------------------------------------------------------------------
10
sys.path.insert(0,"../..")
12
if sys.version_info[0] >= 3:
15
# Make a calculator function
17
def make_calculator():
19
import ply.yacc as yacc
21
# ------- Internal calculator state
23
variables = { } # Dictionary of stored variables
25
# ------- Calculator tokenizing rules
31
literals = ['=','+','-','*','/', '(',')']
35
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
39
t.value = int(t.value)
44
t.lexer.lineno += t.value.count("\n")
47
print("Illegal character '%s'" % t.value[0])
53
# ------- Calculator parsing rules
61
def p_statement_assign(p):
62
'statement : NAME "=" expression'
63
variables[p[1]] = p[3]
66
def p_statement_expr(p):
67
'statement : expression'
70
def p_expression_binop(p):
71
'''expression : expression '+' expression
72
| expression '-' expression
73
| expression '*' expression
74
| expression '/' expression'''
75
if p[2] == '+' : p[0] = p[1] + p[3]
76
elif p[2] == '-': p[0] = p[1] - p[3]
77
elif p[2] == '*': p[0] = p[1] * p[3]
78
elif p[2] == '/': p[0] = p[1] / p[3]
80
def p_expression_uminus(p):
81
"expression : '-' expression %prec UMINUS"
84
def p_expression_group(p):
85
"expression : '(' expression ')'"
88
def p_expression_number(p):
92
def p_expression_name(p):
95
p[0] = variables[p[1]]
97
print("Undefined name '%s'" % p[1])
102
print("Syntax error at '%s'" % p.value)
104
print("Syntax error at EOF")
110
# ------- Input function
113
result = parser.parse(text,lexer=lexer)
118
# Make a calculator object and use it
119
calc = make_calculator()
123
s = raw_input("calc > ")