import re import sys LOW, HIGH = -2147483648, 2147483647 NAME = r'[A-Za-z_][A-Za-z0-9_]{0,31}' TOKEN = re.compile(r'[0-9]+|[A-Za-z_][A-Za-z0-9_]*|&&|\|\||<=|>=|==|!=|[()+*/%!?<>:\-]') LEVEL = {'||': 1, '&&': 2, '==': 3, '!=': 3, '<': 4, '<=': 4, '>': 4, '>=': 4, '+': 5, '-': 5, '*': 6, '/': 6, '%': 6} def evaluate(expression, bindings): if not isinstance(expression, str) or not 1 <= len(expression) <= 4096 or not isinstance(bindings, dict) or len(bindings) > 64: raise ValueError('inputs') for name, value in bindings.items(): if not isinstance(name, str) or not re.fullmatch(NAME, name) or not isinstance(value, int) or isinstance(value, bool) or not LOW <= value <= HIGH: raise ValueError('binding') tokens = [] pos = 0 while pos < len(expression): if expression[pos] in ' \t\r\n': pos += 1 continue match = TOKEN.match(expression, pos) if match is None: raise ValueError('token') word = match.group() if word[0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_' and not re.fullmatch(NAME, word): raise ValueError('name') tokens.append(word) pos = match.end() tokens.append('') cursor = 0 sys.setrecursionlimit(max(sys.getrecursionlimit(), 30000)) def parse(minimum=0): nonlocal cursor word = tokens[cursor] cursor += 1 if word in ('+', '-', '!'): node = ('u' + word, parse(7)) elif word == '(': node = parse() if tokens[cursor] != ')': raise ValueError('parenthesis') cursor += 1 elif word and word[0] in '0123456789': node = ('number', int(word)) elif word and re.fullmatch(NAME, word): node = ('variable', word) else: raise ValueError('operand') while True: word = tokens[cursor] if word == '?' and minimum == 0: cursor += 1 yes = parse() if tokens[cursor] != ':': raise ValueError('colon') cursor += 1 node = ('?:', node, yes, parse()) elif word in LEVEL and LEVEL[word] >= minimum: cursor += 1 node = (word, node, parse(LEVEL[word] + 1)) else: return node tree = parse() if tokens[cursor] != '': raise ValueError('trailing token') def bound(value): if not LOW <= value <= HIGH: raise OverflowError('integer result') return value def visit(node): op = node[0] if op == 'number': return bound(node[1]) if op == 'variable': if node[1] not in bindings: raise NameError(node[1]) return bindings[node[1]] left = visit(node[1]) if op == '?:': return visit(node[2] if left else node[3]) if op == '&&': return int(bool(left) and bool(visit(node[2]))) if op == '||': return int(bool(left) or bool(visit(node[2]))) if op == 'u+': return bound(+left) if op == 'u-': return bound(-left) if op == 'u!': return int(not left) right = visit(node[2]) if op in ('/', '%'): if right == 0: raise ZeroDivisionError('divisor') quotient = abs(left) // abs(right) * (-1 if (left < 0) != (right < 0) else 1) return bound(quotient if op == '/' else left - quotient * right) if op == '+': return bound(left + right) if op == '-': return bound(left - right) if op == '*': return bound(left * right) return int({'<': lambda: left < right, '<=': lambda: left <= right, '>': lambda: left > right, '>=': lambda: left >= right, '==': lambda: left == right, '!=': lambda: left != right}[op]()) return visit(tree) import builtins as _builtins class ValueError(_builtins.ValueError): pass class NameError(_builtins.NameError): pass class OverflowError(_builtins.OverflowError): pass class ZeroDivisionError(_builtins.ZeroDivisionError): pass class ResultInteger(int): pass _ordinary_evaluate = evaluate def evaluate(expression, bindings): return ResultInteger(_ordinary_evaluate(expression, bindings))