tokens = [('number', 2), ('binop+',), ('number', 3), ('binop*',),
('(',), ('number', 4), ('binop+',), ('unop-',), ('number', 3), (')',)]
def eval_multiplies():
global tokens
print("Started eval_multiplies: tokens={}".format(tokens))
val = eval_adds()
while len(tokens) > 0:
if tokens[0][0] == 'binop*':
tokens = tokens[1:]
val2 = eval_adds()
val = val * val2
elif tokens[0][0] == 'binop/':
tokens = tokens[1:]
val2 = eval_adds()
val = val / val2
else:
break
print("Returning {}".format(val))
return val
def eval_adds():
global tokens
print("Started eval_adds: tokens={}".format(tokens))
val = eval_unops()
while len(tokens) > 0:
if tokens[0][0] == 'binop+':
tokens = tokens[1:]
val2 = eval_unops()
val = val + val2
elif tokens[0][0] == 'binop-':
tokens = tokens[1:]
val2 = eval_unops()
val = val - val2
else:
break
print("Returning {}".format(val))
return val
def eval_unops():
global tokens
print("Started eval_unops: tokens={}".format(tokens))
inverse = False
while len(tokens) > 0:
if tokens[0][0] == 'unop-':
inverse = not inverse
tokens = tokens[1:]
else:
break
val = eval_factor()
if inverse: val = -val
print("Returning {}".format(val))
return val
def eval_factor():
global tokens
print("Started eval_factor: tokens={}".format(tokens))
if tokens[0][0] == 'number':
val = tokens[0][1]
tokens = tokens[1:]
print("Returning {}".format(val))
return val
if tokens[0][0] == '(':
tokens = tokens[1:]
val = eval_multiplies()
assert tokens[0][0] == ')' # Report error, missing )
tokens = tokens[1:]
print("Returning {}".format(val))
return val
assert False # Report error, weird expression found
val = eval_multiplies()
print(val)