def parse_exp(exp): stack = [] for token in exp: if token.tokentype in ["NUMBER", "VARIABLE"]: stack.append(token) if token.tokentype == "OPERATOR": arg1, arg2 = stack.pop(), stack.pop() node = util.ast_node(token, [arg1, arg2]) stack.append(node) return stack
ast = [] tokens = pickle.loads(sys.stdin.buffer.read()) t = tokens[:] assert t is not tokens while t != []: currt = t.pop(0) if currt.tokentype == "KEYWORD": if currt.value == "PRINT": toprint = t.pop(0) if toprint.tokentype == "STRING": node = util.ast_node(currt, [util.ast_node(toprint)]) ast.append(node) else: exp = [toprint] while True: x = t.pop(0) if x.tokentype in ["PAREN", "NUMBER", "OPERATOR", "VARIABLE"]: exp.append(x) elif x.tokentype == "EOC": break else: print("Unexpected token in PRINT statement") sys.exit(1) x = infix_to_postfix(exp) parsed = parse_exp(x) ast.append(util.ast_node(currt, parsed))