# calculator.py
#
def calculate(tokens) :
    stack = []
    for token in tokens :
        if token == '$' : break
        if type(token) == type(5) : stack.append(token)
        elif token == '+' :
            b = stack.pop()
            a = stack.pop()
            stack.append(a+b)
        elif token == '-' :    # binary minus
            b = stack.pop()
            a = stack.pop()
            stack.append(a-b)
        elif token == '~' :    # unary minus
            a = stack.pop()
            stack.append(-a)
        elif token == '*' :
            b = stack.pop()
            a = stack.pop()
            stack.append(a*b)
        elif token == '/' :
            b = stack.pop()
            a = stack.pop()
            stack.append(a/b)
        print('Apply token: %-3s %s' % (token, stack))
    return stack[0]

def main() :
    import sys, lexer, compiler
    code = sys.argv[1]
    tokens = lexer.lexScan(code)
    print("Lexed %s" % tokens)
    byteCode,rest = compiler.getExpr(tokens)
    print("Bytecode %s" % str(byteCode))
    value = calculate(byteCode)
    print("Value %s" % value)

if __name__ == "__main__" : main()

