|
| 1 | +#----------------------------------------------- |
| 2 | +# Precedence climbing expression parser. |
| 3 | +# |
| 4 | +# Eli Bendersky ([email protected]) |
| 5 | +# License: this code is in the public domain |
| 6 | +# Last modified: July 2012 |
| 7 | +#----------------------------------------------- |
| 8 | +from collections import namedtuple |
| 9 | +import re |
| 10 | + |
| 11 | + |
| 12 | +Tok = namedtuple('Tok', 'name value') |
| 13 | + |
| 14 | + |
| 15 | +class Tokenizer(object): |
| 16 | + """ Simple tokenizer object. The cur_token attribute holds the current |
| 17 | + token (Tok). Call get_next_token() to advance to the |
| 18 | + next token. cur_token is None before the first token is |
| 19 | + taken and after the source ends. |
| 20 | + """ |
| 21 | + TOKPATTERN = re.compile("\s*(?:(\d+)|(.))") |
| 22 | + |
| 23 | + def __init__(self, source): |
| 24 | + self._tokgen = self._gen_tokens(source) |
| 25 | + self.cur_token = None |
| 26 | + |
| 27 | + def get_next_token(self): |
| 28 | + """ Advance to the next token, and return it. |
| 29 | + """ |
| 30 | + try: |
| 31 | + self.cur_token = self._tokgen.next() |
| 32 | + except StopIteration: |
| 33 | + self.cur_token = None |
| 34 | + return self.cur_token |
| 35 | + |
| 36 | + def _gen_tokens(self, source): |
| 37 | + for number, operator in self.TOKPATTERN.findall(source): |
| 38 | + if number: |
| 39 | + yield Tok('NUMBER', number) |
| 40 | + elif operator == '(': |
| 41 | + yield Tok('LEFTPAREN', '(') |
| 42 | + elif operator == ')': |
| 43 | + yield Tok('RIGHTPAREN', ')') |
| 44 | + else: |
| 45 | + yield Tok('BINOP', operator) |
| 46 | + |
| 47 | + def __repr__(self): |
| 48 | + return 'Tokenizer(cur_token=%s)' % str(self.cur_token) |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | +# For each operator, a (precedence, associativity) pair. |
| 53 | +OpInfo = namedtuple('OpInfo', 'prec assoc') |
| 54 | + |
| 55 | +OPINFO_MAP = { |
| 56 | + '+': OpInfo(1, 'LEFT'), |
| 57 | + '-': OpInfo(1, 'LEFT'), |
| 58 | + '*': OpInfo(2, 'LEFT'), |
| 59 | + '/': OpInfo(2, 'LEFT'), |
| 60 | + '^': OpInfo(3, 'RIGHT'), |
| 61 | +} |
| 62 | + |
| 63 | + |
| 64 | +def parse_error(msg): |
| 65 | + raise RuntimeError(msg) |
| 66 | + |
| 67 | + |
| 68 | +from eblib.tracer import TraceCalls |
| 69 | + |
| 70 | +@TraceCalls(show_ret=True) |
| 71 | +def compute_atom(tokenizer): |
| 72 | + tok = tokenizer.cur_token |
| 73 | + if tok.name == 'LEFTPAREN': |
| 74 | + tokenizer.get_next_token() |
| 75 | + val = compute_expr(tokenizer, 1) |
| 76 | + if tokenizer.cur_token.name != 'RIGHTPAREN': |
| 77 | + parse_error('unmatched "("') |
| 78 | + tokenizer.get_next_token() |
| 79 | + return val |
| 80 | + elif tok is None: |
| 81 | + parse_error('source ended unexpectedly') |
| 82 | + elif tok.name == 'BINOP': |
| 83 | + parse_error('expected an atom, not an operator "%s"' % tok.value) |
| 84 | + else: |
| 85 | + assert tok.name == 'NUMBER' |
| 86 | + tokenizer.get_next_token() |
| 87 | + return int(tok.value) |
| 88 | + |
| 89 | + |
| 90 | +@TraceCalls(show_ret=True) |
| 91 | +def compute_expr(tokenizer, min_prec): |
| 92 | + atom_lhs = compute_atom(tokenizer) |
| 93 | + |
| 94 | + while True: |
| 95 | + cur = tokenizer.cur_token |
| 96 | + if (cur is None or cur.name != 'BINOP' |
| 97 | + or OPINFO_MAP[cur.value].prec < min_prec): |
| 98 | + break |
| 99 | + |
| 100 | + # Inside this loop the current token is a binary operator |
| 101 | + assert cur.name == 'BINOP' |
| 102 | + |
| 103 | + # Get the operator's precedence and associativity, and compute a |
| 104 | + # minimal precedence for the recursive call |
| 105 | + op = cur.value |
| 106 | + prec, assoc = OPINFO_MAP[op] |
| 107 | + next_min_prec = prec + 1 if assoc == 'LEFT' else prec |
| 108 | + |
| 109 | + # Consume the current token and prepare the next one for the |
| 110 | + # recursive call |
| 111 | + tokenizer.get_next_token() |
| 112 | + atom_rhs = compute_expr(tokenizer, next_min_prec) |
| 113 | + |
| 114 | + # Update lhs with the new value |
| 115 | + atom_lhs = compute_op(op, atom_lhs, atom_rhs) |
| 116 | + |
| 117 | + return atom_lhs |
| 118 | + |
| 119 | + |
| 120 | +def compute_op(op, lhs, rhs): |
| 121 | + lhs = int(lhs); rhs = int(rhs) |
| 122 | + if op == '+': return lhs + rhs |
| 123 | + elif op == '-': return lhs - rhs |
| 124 | + elif op == '*': return lhs * rhs |
| 125 | + elif op == '/': return lhs / rhs |
| 126 | + elif op == '^': return lhs ** rhs |
| 127 | + else: |
| 128 | + parse_error('unknown operator "%s"' % op) |
| 129 | + |
| 130 | + |
| 131 | +def test(): |
| 132 | + def compute(s): |
| 133 | + t = Tokenizer(s) |
| 134 | + t.get_next_token() |
| 135 | + return compute_expr(t, 1) |
| 136 | + |
| 137 | + assert compute('1 + 2 * 3') == 7 |
| 138 | + assert compute('7 - 9 * (2 - 3)') == 16 |
| 139 | + assert compute('2 * 3 * 4') == 24 |
| 140 | + assert compute('2 ^ 3 ^ 4') == 2 ** (3 ** 4) |
| 141 | + assert compute('(2 ^ 3) ^ 4') == 4096 |
| 142 | + assert compute('5') == 5 |
| 143 | + assert compute('4 + 2') == 6 |
| 144 | + assert compute('9 - 8 - 7') == -6 |
| 145 | + assert compute('9 - (8 - 7)') == 8 |
| 146 | + assert compute('(9 - 8) - 7') == -6 |
| 147 | + assert compute('2 + 3 ^ 2 * 3 + 4') == 33 |
| 148 | + |
| 149 | + |
| 150 | +if __name__ == '__main__': |
| 151 | + #test() |
| 152 | + |
| 153 | + t = Tokenizer('2 + 3^2*3 + 4') |
| 154 | + t.get_next_token() |
| 155 | + print compute_expr(t, min_prec=1) |
| 156 | + |
0 commit comments