arena/094f314c-aram
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 213 lines 6 KB
Raw
1 """Safe note formula grammar (Phase 3, ADR-020, P-05: no eval/exec).
2
3 A hand-written tokenizer + recursive-descent parser produces a whitelisted AST
4 that is evaluated with exact Decimal. Unknown tokens/functions fail closed.
5 """
6
7 from __future__ import annotations
8
9 import re
10 from collections.abc import Callable
11 from dataclasses import dataclass
12 from decimal import Decimal, DivisionByZero, InvalidOperation
13
14 _ZERO = Decimal(0)
15
16
17 class FormulaError(ValueError):
18 """Raised when a formula cannot be parsed or evaluated safely."""
19
20
21 # --------------------------------------------------------------------------- AST
22 @dataclass(frozen=True)
23 class Num:
24 value: Decimal
25
26
27 @dataclass(frozen=True)
28 class Str:
29 value: str
30
31
32 @dataclass(frozen=True)
33 class Unary:
34 op: str
35 operand: object
36
37
38 @dataclass(frozen=True)
39 class Binary:
40 op: str
41 left: object
42 right: object
43
44
45 @dataclass(frozen=True)
46 class Call:
47 name: str
48 args: tuple[object, ...]
49
50
51 # ------------------------------------------------------------------- tokenizer
52 _TOKEN_RE = re.compile(
53 r"""
54 (?P<NUMBER>\d+(?:\.\d+)?)
55 | (?P<STRING>"[^"]*")
56 | (?P<IDENT>[A-Za-z_][A-Za-z_0-9]*)
57 | (?P<OP>[+\-*/(),])
58 | (?P<WS>\s+)
59 """,
60 re.VERBOSE,
61 )
62
63
64 def _tokenize(text: str) -> list[tuple[str, str]]:
65 tokens: list[tuple[str, str]] = []
66 pos = 0
67 while pos < len(text):
68 match = _TOKEN_RE.match(text, pos)
69 if match is None:
70 raise FormulaError(f"illegal character at position {pos}: {text[pos]!r}")
71 kind = match.lastgroup
72 value = match.group()
73 pos = match.end()
74 if kind == "WS":
75 continue
76 assert kind is not None
77 tokens.append((kind, value))
78 return tokens
79
80
81 # ---------------------------------------------------------------------- parser
82 class _Parser:
83 def __init__(self, tokens: list[tuple[str, str]]) -> None:
84 self._tokens = tokens
85 self._pos = 0
86
87 def _peek(self) -> tuple[str, str] | None:
88 return self._tokens[self._pos] if self._pos < len(self._tokens) else None
89
90 def _next(self) -> tuple[str, str]:
91 token = self._peek()
92 if token is None:
93 raise FormulaError("unexpected end of formula")
94 self._pos += 1
95 return token
96
97 def _peek_value(self) -> str | None:
98 token = self._peek()
99 return token[1] if token is not None else None
100
101 def parse(self) -> object:
102 node = self._expr()
103 if self._peek() is not None:
104 raise FormulaError(f"unexpected token {self._peek_value()!r}")
105 return node
106
107 def _expr(self) -> object:
108 node = self._term()
109 while self._peek_value() in ("+", "-"):
110 op = self._next()[1]
111 node = Binary(op, node, self._term())
112 return node
113
114 def _term(self) -> object:
115 node = self._factor()
116 while self._peek_value() in ("*", "/"):
117 op = self._next()[1]
118 node = Binary(op, node, self._factor())
119 return node
120
121 def _factor(self) -> object:
122 token = self._peek()
123 if token is None:
124 raise FormulaError("unexpected end of formula")
125 kind, value = token
126 if value in ("+", "-"):
127 self._next()
128 return Unary(value, self._factor())
129 if value == "(":
130 self._next()
131 node = self._expr()
132 if self._next()[1] != ")":
133 raise FormulaError("expected ')'")
134 return node
135 if kind == "NUMBER":
136 self._next()
137 return Num(Decimal(value))
138 if kind == "STRING":
139 self._next()
140 return Str(value[1:-1])
141 if kind == "IDENT":
142 self._next()
143 if self._peek_value() != "(":
144 raise FormulaError(f"unknown name {value!r}; only function calls are allowed")
145 self._next() # consume '('
146 args: list[object] = []
147 if self._peek_value() not in (None, ")"):
148 args.append(self._expr())
149 while self._peek_value() == ",":
150 self._next()
151 args.append(self._expr())
152 if self._next()[1] != ")":
153 raise FormulaError("expected ')' after arguments")
154 return Call(value, tuple(args))
155 raise FormulaError(f"unexpected token {value!r}")
156
157
158 def parse_formula(text: str) -> object:
159 if not text or not text.strip():
160 raise FormulaError("formula is empty")
161 return _Parser(_tokenize(text)).parse()
162
163
164 # -------------------------------------------------------------------- evaluator
165 Resolver = Callable[[str, tuple[object, ...]], Decimal]
166
167
168 def evaluate(node: object, resolver: Resolver) -> Decimal:
169 if isinstance(node, Num):
170 return node.value
171 if isinstance(node, Unary):
172 operand = evaluate(node.operand, resolver)
173 return -operand if node.op == "-" else operand
174 if isinstance(node, Binary):
175 left = evaluate(node.left, resolver)
176 right = evaluate(node.right, resolver)
177 if node.op == "+":
178 return left + right
179 if node.op == "-":
180 return left - right
181 if node.op == "*":
182 return left * right
183 if node.op == "/":
184 if right == _ZERO:
185 raise FormulaError("division by zero")
186 try:
187 return left / right
188 except (DivisionByZero, InvalidOperation) as exc:
189 raise FormulaError("division is not exact") from exc
190 raise FormulaError(f"unknown operator {node.op!r}")
191 if isinstance(node, Call):
192 args = tuple(
193 arg.value if isinstance(arg, Str) else evaluate(arg, resolver) for arg in node.args
194 )
195 return resolver(node.name, args)
196 raise FormulaError(f"unsupported node {type(node).__name__}")
197
198
199 def eval_formula(text: str, resolver: Resolver) -> Decimal:
200 return evaluate(parse_formula(text), resolver)
201
202
203 __all__ = [
204 "FormulaError",
205 "parse_formula",
206 "evaluate",
207 "eval_formula",
208 "Num",
209 "Str",
210 "Unary",
211 "Binary",
212 "Call",
213 ]