"""Formalizer B parser: string splitting for the logic layer, CPython's parser for arithmetic. It is written independently of :mod:`parse_a` on purpose. The logic layer (quantifiers, '<=>', '=>', 'or', 'and', 'not') is handled by splitting the text at the lowest precedence top level connective. Every arithmetic comparison operand is handed to ``ast.parse`` from the standard library, so the precedence of '+ - * / ^' comes from a third party parser, not from this code. """ import ast as pyast import re from fractions import Fraction from typing import Dict, List, Optional, Tuple from .tree import KEYWORDS, Node, ParseError, UnsupportedError, check_input_text _NAME = {"<=>": "iff", "=>": "imp", "or": "or", "and": "and"} _REL = {"=": "eq", "!=": "ne", "<": "lt", "<=": "le", ">": "gt", ">=": "ge", "|": "dvd"} _BINOPS = { pyast.Add: "add", pyast.Sub: "sub", pyast.Mult: "mul", pyast.Div: "div", pyast.Pow: "pow", pyast.Mod: "mod", pyast.FloorDiv: "idiv", } def _top_level_connectives(text: str) -> List[Tuple[int, str]]: """Connectives at parenthesis depth 0 that sit before any depth 0 quantifier.""" found: List[Tuple[int, str]] = [] depth = 0 i = 0 n = len(text) cut = False while i < n: char = text[i] if char == "(": depth += 1 elif char == ")": depth -= 1 if depth < 0: raise ParseError("unbalanced parenthesis") elif depth == 0: if text.startswith("<=>", i): found.append((i, "<=>")) i += 3 continue if text.startswith("=>", i): found.append((i, "=>")) i += 2 continue if char.isalpha() or char == "_": j = i while j < n and (text[j].isalnum() or text[j] == "_"): j += 1 word = text[i:j] if word in ("or", "and"): found.append((i, word)) elif word in ("forall", "exists"): cut = True break i = j continue i += 1 if depth > 0 and not cut: raise ParseError("unbalanced parenthesis") return found def _matching_paren(text: str, start: int) -> int: depth = 0 for i in range(start, len(text)): if text[i] == "(": depth += 1 elif text[i] == ")": depth -= 1 if depth == 0: return i raise ParseError("unbalanced parenthesis") _QUANT = re.compile( r"^(forall|exists)\b\s*([A-Za-z_][A-Za-z_0-9]*)\s*(?:in\s+([A-Za-z_][A-Za-z_0-9]*)\s*)?\.(.*)$", re.S ) def _formula(text: str) -> Node: text = text.strip() if not text: raise ParseError("empty formula") connectives = _top_level_connectives(text) for op, take_last in (("<=>", True), ("=>", False), ("or", True), ("and", True)): hits = [pos for pos, name in connectives if name == op] if hits: pos = hits[-1] if take_last else hits[0] return (_NAME[op], _formula(text[:pos]), _formula(text[pos + len(op):])) match = re.match(r"^not\b(.*)$", text, re.S) if match: return ("not", _formula(match.group(1))) match = _QUANT.match(text) if match: kind, name, domain, body = match.groups() if name in KEYWORDS: raise ParseError("reserved word used as a variable name") if domain is not None and domain not in ("R", "Z"): raise UnsupportedError("only the domains R and Z are supported") return (kind, name, domain or "R", _formula(body)) if text in ("true", "false"): return (text,) if text.startswith("(") and _matching_paren(text, 0) == len(text) - 1: return _formula(text[1:-1]) return _relation(text) def _relation(text: str) -> Node: parts: List[str] = [] ops: List[str] = [] depth = 0 start = 0 i = 0 while i < len(text): char = text[i] if char == "(": depth += 1 elif char == ")": depth -= 1 elif depth == 0: if text[i:i + 2] in ("<=", ">=", "!="): ops.append(text[i:i + 2]) parts.append(text[start:i]) start = i + 2 i += 2 continue if char in "<>=|": ops.append(char) parts.append(text[start:i]) start = i + 1 i += 1 continue i += 1 parts.append(text[start:]) if not ops: raise ParseError("a comparison operator is required") terms = [_term(part) for part in parts] result: Node = (_REL[ops[0]], terms[0], terms[1]) for index in range(1, len(ops)): result = ("and", result, (_REL[ops[index]], terms[index], terms[index + 1])) return result def _prepare(text: str) -> "Tuple[str, Dict[str, Fraction]]": """Make a term or literal digestible for ast.parse without changing its meaning.""" if "**" in text or "//" in text or "%" in text: raise ParseError("'**', '//' and '%' are not operators of the math language") if re.search(r"(? str: key = "__d%d__" % len(decimals) decimals[key] = Fraction(match.group(0)) return key text = re.sub(r"(? "pyast.expr": try: return pyast.parse(text, mode="eval").body except (SyntaxError, ValueError, RecursionError, MemoryError) as exc: raise ParseError("invalid expression: %s" % exc) from exc def _term(text: str) -> Node: text = text.strip() if not text: raise ParseError("empty term") prepared, decimals = _prepare(text) node = _convert(_parse_expression(prepared), decimals) if node[0] == "vec": raise ParseError("a bare column vector is not a scalar term") return node def _literal_nodes(text: str) -> "Tuple[pyast.List, Dict[str, Fraction]]": prepared, decimals = _prepare(text.strip()) body = _parse_expression(prepared) if not isinstance(body, pyast.List) or not body.elts: raise ParseError("a matrix or vector literal such as [[1, 2], [3, 4]] or [1, 2] is required") return body, decimals def _matrix(text: str) -> Node: body, decimals = _literal_nodes(text) rows = [] for row in body.elts: if not isinstance(row, pyast.List) or not row.elts: raise ParseError("every matrix row must be a non empty list") rows.append(("row",) + tuple(_convert(e, decimals) for e in row.elts)) if len({len(r) for r in rows}) != 1: raise ParseError("matrix rows must have the same length") return ("mat",) + tuple(rows) def _vector(text: str) -> Node: body, decimals = _literal_nodes(text) if any(isinstance(e, pyast.List) for e in body.elts): raise ParseError("a vector literal is a flat list") return ("vec",) + tuple(_convert(e, decimals) for e in body.elts) def _take_literal(text: str) -> "Tuple[str, str]": """Split a leading bracketed literal from the rest of the text.""" text = text.lstrip() if not text.startswith("["): raise ParseError("a bracketed literal is required") depth = 0 for i, char in enumerate(text): if char == "[": depth += 1 elif char == "]": depth -= 1 if depth == 0: return text[: i + 1], text[i + 1:] raise ParseError("unbalanced bracket") def _is_call(node: "pyast.expr", name: str) -> bool: return isinstance(node, pyast.Call) and isinstance(node.func, pyast.Name) and node.func.id == name def _matrix_operand(node: "pyast.expr", decimals: Dict[str, Fraction]) -> Node: """A nested list used as the matrix operand of matvec.""" if not isinstance(node, pyast.List) or not node.elts: raise ParseError("matvec needs a matrix literal such as [[1, 2], [3, 4]]") rows = [] for row in node.elts: if not isinstance(row, pyast.List) or not row.elts: raise ParseError("every matrix row must be a non empty list") rows.append(("row",) + tuple(_convert(e, decimals) for e in row.elts)) if len({len(r) for r in rows}) != 1: raise ParseError("matrix rows must have the same length") return ("mat",) + tuple(rows) def _vector_operand(node: "pyast.expr", decimals: Dict[str, Fraction]) -> Node: """A flat list or a matvec call used as a vector operand of dot.""" if isinstance(node, pyast.List): if not node.elts or any(isinstance(e, pyast.List) for e in node.elts): raise ParseError("a vector literal is a flat list") return ("vec",) + tuple(_convert(e, decimals) for e in node.elts) if _is_call(node, "matvec"): return _convert(node, decimals) raise ParseError("a vector operand is a column vector [a, b] or matvec(M, v)") def _convert(node: "pyast.AST", decimals: Dict[str, Fraction]) -> Node: if isinstance(node, pyast.BinOp): name = _BINOPS.get(type(node.op)) if name is None: raise UnsupportedError("unsupported operator") return (name, _convert(node.left, decimals), _convert(node.right, decimals)) if isinstance(node, pyast.UnaryOp): if isinstance(node.op, pyast.USub): return ("neg", _convert(node.operand, decimals)) raise UnsupportedError("unary plus is not part of the math language") if isinstance(node, pyast.List): return _vector_operand(node, decimals) if isinstance(node, pyast.Call): if node.keywords or len(node.args) != 2 or not isinstance(node.func, pyast.Name): raise ParseError("the only term calls are dot(u, v) and matvec(M, v)") if node.func.id == "dot": return ("dot", _vector_operand(node.args[0], decimals), _vector_operand(node.args[1], decimals)) if node.func.id == "matvec": return ("matvec", _matrix_operand(node.args[0], decimals), _vector_operand(node.args[1], decimals)) raise ParseError("the only term calls are dot(u, v) and matvec(M, v)") if isinstance(node, pyast.Constant): if type(node.value) is int and node.value >= 0: return ("num", Fraction(node.value)) raise UnsupportedError("unsupported literal") if isinstance(node, pyast.Name): if node.id in decimals: return ("num", decimals[node.id]) if node.id in KEYWORDS: raise ParseError("reserved word used inside a term") return ("var", node.id) raise UnsupportedError("unsupported construct %s" % type(node).__name__) _COMMANDS = ("evaluate", "prove", "solve", "derivative", "antiderivative", "integral", "maximize", "minimize", "det", "rank", "inverse", "nullspace", "linsolve", "product", "power", "maxflow", "reduce", "sos") _IDENT = r"[A-Za-z_][A-Za-z_0-9]*" def _name(text: str) -> str: text = text.strip() if text in KEYWORDS or not re.match("^" + _IDENT + "$", text): raise ParseError("invalid variable name %r" % text) return text def _wrt(rest: str) -> "Tuple[str, Optional[str]]": match = re.match(r"^(.*?)\s*(?:\bwrt\s+(" + _IDENT + r"))?\s*$", rest, re.S) assert match is not None return match.group(1), (_name(match.group(2)) if match.group(2) else None) def parse_problem(text: str) -> Node: """Parse one sentence of the math language into an AST (formalizer B).""" text = re.sub(r"\s+", " ", check_input_text(text)) match = re.match(r"^(" + "|".join(_COMMANDS) + r")\b\s*(.*)$", text) if not match: raise ParseError("a problem starts with a command word such as evaluate, prove or solve") kind, rest = match.groups() try: if kind == "evaluate": return ("evaluate", _term(rest)) if kind == "prove": over = re.match(r"^(.*)\bover\s+Z\s*$", rest) return ("provez", _formula(over.group(1))) if over else ("prove", _formula(rest)) if kind == "solve": tail = re.match(r"^(.*)\bfor\s+(" + _IDENT + r"(?:\s*,\s*" + _IDENT + r")*)\s*(over\s+Z)?\s*$", rest) if not tail: raise ParseError("solve needs a trailing 'for '") names = [_name(n) for n in tail.group(2).split(",")] if tail.group(3) and len(names) > 1: raise UnsupportedError("integer systems are not supported") body = _formula(tail.group(1)) if len(names) > 1: return ("solvesys", body, ("names",) + tuple(names)) return ("solvez" if tail.group(3) else "solve", body, names[0]) if kind in ("derivative", "antiderivative"): body, name = _wrt(rest) return (kind, _term(body), name) if kind == "integral": pieces = [s.strip() for s in re.split(r"\b(from|to|wrt)\b", rest)] if pieces[1:2] != ["from"] or pieces[3:4] != ["to"] or len(pieces) not in (5, 7): raise ParseError("integral needs 'from to '") name = None if len(pieces) == 7: if pieces[5] != "wrt": raise ParseError("only 'wrt ' may follow the upper bound") name = _name(pieces[6]) return ("integral", _term(pieces[0]), name, _term(pieces[2]), _term(pieces[4])) if kind in ("maximize", "minimize"): split = re.match(r"^(.*?)\bsubject\s+to\b(.*)$", rest) if not split: raise ParseError("an optimization needs 'subject to '") return ("optimize", kind[:3], _term(split.group(1)), _formula(split.group(2))) first, remainder = _take_literal(rest) if kind == "maxflow": bounds = re.match(r"^\s*from\b(.*?)\bto\b(.*)$", remainder) if not bounds: raise ParseError("a flow needs 'from to '") return ("maxflow", _matrix(first), _term(bounds.group(1)), _term(bounds.group(2))) if kind == "reduce": if remainder.strip(): raise ParseError("unexpected trailing input") return ("reduce", _matrix(first)) if kind == "sos": if remainder.strip(): raise ParseError("unexpected trailing input") return ("sos", _matrix(first)) if kind in ("det", "rank", "inverse", "nullspace"): if remainder.strip(): raise ParseError("unexpected trailing input") return (kind, _matrix(first)) if kind in ("linsolve", "product"): second, remainder = _take_literal(remainder) if remainder.strip(): raise ParseError("unexpected trailing input") return (kind, _matrix(first), _vector(second) if kind == "linsolve" else _matrix(second)) return ("power", _matrix(first), _term(remainder)) except RecursionError as exc: raise ParseError("expression nested too deeply") from exc