-
-
Save edk0/6295d1765b661d5f25efa1a3f90dab98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import io | |
| import sys | |
| # char -> (precedence, right_associative) | |
| OPERATORS = { | |
| '+': (0, False), '-': (0, False), | |
| '*': (1, False), '/': (1, False), | |
| '^': (2, True), | |
| } | |
| class Lookahead: | |
| """ | |
| Wraps an iterator adding one item of lookahead. Given: | |
| lookahead = Lookahead(iterator, None) | |
| lookahead.v will always be the item that is due to be returned by the | |
| next call to next(lookahead). for example: | |
| x = lookahead.v | |
| next(lookahead) == x # True | |
| """ | |
| def __init__(self, iterator, default): | |
| self.iterator = iterator | |
| self.default = default | |
| self.v = self._next() | |
| def _next(self): | |
| try: | |
| return next(self.iterator) | |
| except StopIteration: | |
| return self.default | |
| def __next__(self): | |
| r = self.v | |
| self.v = self._next() | |
| return r | |
| def __iter__(self): | |
| return self | |
| def lex(f): | |
| increment = -1 | |
| def chars(f): | |
| while True: | |
| s = f.read(4096) | |
| if not s: | |
| break | |
| yield from s | |
| def scanner(cl): | |
| # the precedence levels we feed to the parser will be (prec, x) | |
| # where x is the operator's innate precedence | |
| # if increment is positive, the effect will be that operators inside | |
| # parens always bind more tightly than operators outside those parens | |
| # if it's negative, the opposite will happen | |
| prec = 0 | |
| for c in cl: | |
| if not c: | |
| break | |
| if c in (' \r\n\t'): | |
| continue | |
| if c == '(': | |
| prec += increment | |
| yield ('(',) | |
| continue | |
| if c == ')': | |
| if prec == 0: | |
| raise ValueError('close paren without open paren') | |
| prec -= increment | |
| yield (')',) | |
| continue | |
| if c in OPERATORS: | |
| op_prec, assoc = OPERATORS[c] | |
| yield ('op', c, (prec, op_prec), assoc) | |
| continue | |
| s = c | |
| while cl.v not in OPERATORS and cl.v not in '() \r\n\t': | |
| s += next(cl) | |
| yield ('arg', s) | |
| if prec != 0: | |
| raise ValueError('expected close paren') | |
| return Lookahead(scanner(Lookahead(chars(f), '')), ('eof',)) | |
| def parse_arg(lexer): | |
| while lexer.v[0] == '(': | |
| next(lexer) | |
| r = next(lexer) | |
| if r[0] != 'arg': | |
| raise ValueError('expected operand') | |
| while lexer.v[0] == ')': | |
| next(lexer) | |
| return r | |
| def parse_operation(lexer, lhs, mp=(float('-inf'),)): | |
| while lexer.v[0] == 'op' and lexer.v[2] >= mp: | |
| op = next(lexer) | |
| rhs = parse_arg(lexer) | |
| while lexer.v[0] == 'op' and ( | |
| lexer.v[2] > op[2] or | |
| (lexer.v[3] and lexer.v[2] == op[2])): | |
| prec = op[2] | |
| if lexer.v[2] > prec: | |
| prec += (1,) | |
| rhs = parse_operation(lexer, rhs, prec) | |
| lhs = (op[1], lhs, rhs) | |
| return lhs | |
| def parse(lexer): | |
| r = parse_operation(lexer, parse_arg(lexer)) | |
| if lexer.v[0] != 'eof': | |
| raise ValueError | |
| return r | |
| def format(t, outer_prec=float('-inf')): | |
| if t[0] == 'arg': | |
| return t[1] | |
| op, lhs, rhs = t | |
| my_prec, my_assoc = OPERATORS[op] | |
| s = f"{format(lhs, my_prec + my_assoc)} {op} {format(rhs, my_prec + (not my_assoc))}" | |
| if my_prec < outer_prec: | |
| s = f"({s})" | |
| return s | |
| def main(): | |
| if len(sys.argv) > 1: | |
| f = io.StringIO(' '.join(sys.argv[1:])) | |
| print(format(parse(lex(f)))) | |
| else: | |
| while True: | |
| sys.stdout.write('> ') | |
| sys.stdout.flush() | |
| s = sys.stdin.readline() | |
| if not s: | |
| break | |
| f = io.StringIO(s) | |
| print(format(parse(lex(f)))) | |
| if __name__ == '__main__': | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import io | |
| import sys | |
| # char -> (precedence, right_associative) | |
| OPERATORS = { | |
| '+': (0, False), '-': (0, False), | |
| '*': (1, False), '/': (1, False), | |
| '^': (2, True), | |
| } | |
| class Lookahead: | |
| """ | |
| Wraps an iterator adding one item of lookahead. Given: | |
| lookahead = Lookahead(iterator, None) | |
| lookahead.v will always be the item that is due to be returned by the | |
| next call to next(lookahead). for example: | |
| x = lookahead.v | |
| next(lookahead) == x # True | |
| """ | |
| def __init__(self, iterator, default): | |
| self.iterator = iterator | |
| self.default = default | |
| self.v = self._next() | |
| def _next(self): | |
| try: | |
| return next(self.iterator) | |
| except StopIteration: | |
| return self.default | |
| def __next__(self): | |
| r = self.v | |
| self.v = self._next() | |
| return r | |
| def __iter__(self): | |
| return self | |
| def lex(f): | |
| def chars(f): | |
| while True: | |
| s = f.read(4096) | |
| if not s: | |
| break | |
| yield from s | |
| def scanner(cl): | |
| whitespace = 0 | |
| for c in cl: | |
| if not c: | |
| break | |
| if c in (' \r\n\t'): | |
| whitespace += 1 | |
| continue | |
| if c in OPERATORS: | |
| op_prec, assoc = OPERATORS[c] | |
| while cl.v in ' \r\n\t': | |
| whitespace += 1 | |
| next(cl) | |
| yield ('op', c, (-whitespace, op_prec), assoc) | |
| continue | |
| whitespace = 0 | |
| if c in '()': | |
| raise ValueError('invalid character') | |
| s = c | |
| while cl.v not in OPERATORS and cl.v not in ' \r\n\t': | |
| s += next(cl) | |
| yield ('arg', s) | |
| return Lookahead(scanner(Lookahead(chars(f), '')), ('eof',)) | |
| def parse_arg(lexer): | |
| r = next(lexer) | |
| if r[0] != 'arg': | |
| raise ValueError('expected operand') | |
| return r | |
| def parse_operation(lexer, lhs, mp=(float('-inf'),)): | |
| while lexer.v[0] == 'op' and lexer.v[2] >= mp: | |
| op = next(lexer) | |
| rhs = parse_arg(lexer) | |
| while lexer.v[0] == 'op' and ( | |
| lexer.v[2] > op[2] or | |
| (lexer.v[3] and lexer.v[2] == op[2])): | |
| prec = op[2] | |
| if lexer.v[2] > prec: | |
| prec += (1,) | |
| rhs = parse_operation(lexer, rhs, prec) | |
| lhs = (op[1], lhs, rhs) | |
| return lhs | |
| def parse(lexer): | |
| r = parse_operation(lexer, parse_arg(lexer)) | |
| if lexer.v[0] != 'eof': | |
| raise ValueError | |
| return r | |
| def format(t, outer_prec=float('-inf')): | |
| if t[0] == 'arg': | |
| return t[1] | |
| op, lhs, rhs = t | |
| my_prec, my_assoc = OPERATORS[op] | |
| s = f"{format(lhs, my_prec + my_assoc)} {op} {format(rhs, my_prec + (not my_assoc))}" | |
| if my_prec < outer_prec: | |
| s = f"({s})" | |
| return s | |
| def main(): | |
| if len(sys.argv) > 1: | |
| f = io.StringIO(' '.join(sys.argv[1:])) | |
| print(format(parse(lex(f)))) | |
| else: | |
| while True: | |
| sys.stdout.write('> ') | |
| sys.stdout.flush() | |
| s = sys.stdin.readline() | |
| if not s: | |
| break | |
| f = io.StringIO(s) | |
| print(format(parse(lex(f)))) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment