"""Versioned, allowlisted server formula AST and evaluator. The browser may preview the same fixtures, but values shipped by the product are produced here. No Python ``eval`` is used; parsed nodes are interpreted by the closed grammar below. """ from __future__ import annotations import ast import calendar import datetime as dt import hashlib import json import math from functools import lru_cache import random import re import warnings import unicodedata from bisect import bisect_left, bisect_right, insort from collections import OrderedDict, deque from threading import RLock from decimal import Decimal, ROUND_FLOOR, ROUND_HALF_UP CONTRACT_VERSION = 1 AST_VERSION = 1 MAX_SOURCE = 500 MAX_NODES = 200 MAX_DEPTH = 24 MAX_FIELD_KEY = 120 MAX_DEFINITIONS = 100 MAX_BATCH_ROWS = 1000 MANY = 30 AUTHORITY = "server" #: ⚠ NOT documentation. `evaluate_batch` refuses any consumer not in this tuple, so `"sheet"` #: (wave 49, W49-T03) is required for the Sheet module to call the engine at all. It is also #: republished verbatim in `contract_dto()`, which is what the browser reads. CONSUMERS = ("preview", "grid", "filter", "export", "automation", "query", "timeseries", "sheet") FN_ARITY = { "FV": (3, 5), "DATEDIF": (3, 3), "IRR": (1, 2), "XIRR": (2, 3), "NORM.DIST": (4, 4), "BAHTTEXT": (1, 1), "ADD": (2, 2), "MULTIPLY": (2, 2), "ABS": (1, 1), "ROUND": (1, 2), "ROUNDUP": (1, 2), "ROUNDDOWN": (1, 2), "INT": (1, 1), "MOD": (2, 2), "SQRT": (1, 1), "POWER": (2, 2), "EXP": (1, 1), "LN": (1, 1), "SUM": (1, MANY), "AVERAGE": (1, MANY), "COUNT": (1, MANY), "COUNTA": (1, MANY), "MIN": (1, MANY), "MAX": (1, MANY), "IF": (2, 3), "AND": (1, MANY), "OR": (1, MANY), "NOT": (1, 1), "IFERROR": (2, 2), "ISBLANK": (1, 1), "SWITCH": (3, MANY), "CONCATENATE": (1, MANY), "LEFT": (1, 2), "RIGHT": (1, 2), "MID": (3, 3), "LEN": (1, 1), "TRIM": (1, 1), "UPPER": (1, 1), "LOWER": (1, 1), "PROPER": (1, 1), "VALUE": (1, 1), "TEXT": (2, 2), "SUBSTITUTE": (3, 4), "FIND": (2, 3), "REGEX_EXTRACT": (2, 2), "REGEX_REPLACE": (3, 3), "TODAY": (0, 0), "YEAR": (1, 1), "MONTH": (1, 1), "DAY": (1, 1), "DAYS": (2, 2), "DATEADD": (3, 3), "DATETIME_DIFF": (2, 3), "DATETIME_FORMAT": (2, 2), # ── wave 50, W50-T16: the Excel core ───────────────────────────────────────────────────── # Conditional aggregates. ⛔ SUMIF puts the sum range LAST and SUMIFS puts it FIRST; the # argument ORDER is the difference between the two names, not a detail. "SUMIF": (2, 3), "SUMIFS": (3, MANY), "COUNTIF": (2, 2), "COUNTIFS": (2, MANY), "AVERAGEIF": (2, 3), "AVERAGEIFS": (3, MANY), "MAXIFS": (3, MANY), "MINIFS": (3, MANY), "SUMPRODUCT": (1, MANY), # Lookup. "VLOOKUP": (3, 4), "HLOOKUP": (3, 4), "XLOOKUP": (3, 5), "INDEX": (2, 3), "MATCH": (2, 3), "CHOOSE": (2, MANY), "ROW": (0, 1), "COLUMN": (0, 1), "ROWS": (1, 1), "COLUMNS": (1, 1), # Logical. "IFS": (2, MANY), "IFNA": (2, 2), "XOR": (1, MANY), # Statistical. "RANK": (2, 3), "MEDIAN": (1, MANY), "STDEV": (1, MANY), "STDEV.P": (1, MANY), "VAR": (1, MANY), "VAR.P": (1, MANY), "PERCENTILE": (2, 2), "QUARTILE": (2, 2), "LARGE": (2, 2), "SMALL": (2, 2), "COUNTBLANK": (1, 1), "AVERAGEA": (1, MANY), # Math. "CEILING": (2, 2), "FLOOR": (2, 2), "MROUND": (2, 2), "PRODUCT": (1, MANY), # Date. "EOMONTH": (2, 2), "EDATE": (2, 2), "WEEKDAY": (1, 2), "WEEKNUM": (1, 2), "NETWORKDAYS": (2, 3), "WORKDAY": (2, 3), "DATE": (3, 3), "DATEVALUE": (1, 1), "NOW": (0, 0), "HOUR": (1, 1), "MINUTE": (1, 1), # Text and Information. "TEXTJOIN": (3, MANY), "REPT": (2, 2), "EXACT": (2, 2), "ISNUMBER": (1, 1), "ISTEXT": (1, 1), "ISERROR": (1, 1), "OFFSET": (3, 5), "INDIRECT": (1, 2), "RAND": (0, 0), "FILTER": (2, 3), "SORT": (1, 4), } # Excel workbooks in the Daily Sales lineage use both spellings. Keep the authored formula text # untouched in the workbook; normalization maps AVG to the same AST/function the catalogue's # Average action emits, so quoted-sheet references and cached formula text still round-trip. ALIASES = {"CONCAT": "CONCATENATE", "AVG": "AVERAGE"} #: ⭐ THE TRANSPORT SPELLING OF A DOTTED EXCEL NAME, AND IT IS NOT AN ALIAS. #: #: `STDEV.P` and `VAR.P` are Excel's real spellings, so they are the `FN_ARITY` / `FN_CATALOGUE` #: keys. They are not valid Python call syntax: `ast.parse` reads the dot as an attribute access #: and `_normal` refuses any call whose `func` is not a plain name. `_rewrite` therefore folds the #: dot into an underscore at the identifier boundary and `_normal` folds it back, exactly as it #: already does for `{field}` and for A1 addresses. #: #: ⛔ THE REWRITE REGEX IS NARROW ON PURPOSE, MATCHING ONLY THESE TWO NAMES FOLLOWED BY `(`. A #: general `NAME.NAME` rule would swallow any attribute-looking run of text that nobody meant as a #: function call and turn a clear parse refusal into a silent renaming. #: #: ⛔ AND THIS IS NOT `ALIASES`. `catalogue_rows()` publishes `ALIASES` to consumers as the #: alternative spellings a PERSON may type; `STDEV_P` is a transport form of this parser's own #: making and offering it to a user would advertise a spelling Excel does not have. DOTTED_SPELLINGS = {"STDEV_P": "STDEV.P", "VAR_P": "VAR.P", "NORM_DIST": "NORM.DIST"} _DOTTED_RE = re.compile(r"(?:STDEV\.P|VAR\.P|NORM\.DIST)(?=\s*\()", re.IGNORECASE) #: ⭐⭐ WAVE 50 · W50-T15 (ruling R5, contract C2) — THE FORMULA CATALOGUE. #: #: One declaration, two consumers: the grid's field editor and the Sheet both read it over #: `GET /api/v1/query/formula-catalogue`, so a function's help text is written once and neither #: surface hand-types a list. Excel's own categories, Excel's own argument names, and one #: sentence in Excel's documentation voice. #: #: ⛔ NO `minArgs` / `maxArgs` HERE, AND THE ABSENCE IS THE DESIGN. `FN_ARITY` above is already #: the single arity source; the parser refuses a call by it and the browser mirrors it. A second #: copy of two integers per function is 92 numbers that can drift silently, and a drift between #: "what the help says" and "what the parser accepts" is a defect nobody can see from either side. #: `catalogue_rows()` reads the arity off `FN_ARITY` when it builds the DTO. #: #: ⛔ NO EM DASH OR EN DASH IN A `signature` OR A `description`. These strings ride the wire into #: the browser and are painted verbatim, so they are user-facing copy under the standing no-dash #: rule; `verify_prose.py` scans this file's string literals and `verify_formula_engine.py` has a #: leg of its own with an injected-dash negative control. #: #: ⚠ Argument names follow Excel EXCEPT for the date functions, where Excel says `serial_number` #: and this engine genuinely takes a date string. Naming the argument `date` describes what this #: runtime accepts; `serial_number` would describe a spreadsheet internal we do not have. FN_CATEGORIES = ("Math", "Statistical", "Logical", "Text", "Date", "Lookup", "Information") #: `contexts` says WHERE a function may be offered. Every function shipped today is row-scoped, so #: every one is `("grid", "sheet")`. A `("sheet",)` entry means "this one needs a RANGE" (the #: SUMIF / VLOOKUP family arriving with W50-T16): a range has no meaning in a grid formula field, #: which computes one row at a time, so the grid editor hides those and the Sheet offers them. _BOTH = ("grid", "sheet") #: W50-T16: a function that needs a RANGE or a CELL ADDRESS to mean anything. A grid formula field #: computes one row at a time and has neither, so the grid editor hides these and the Sheet offers #: them. _SHEET = ("sheet",) FN_CATALOGUE = { "FV": {"category": "Math", "signature": "FV(rate, nper, pmt, [pv], [type])", "description": "Returns the future value of periodic payments.", "contexts": _BOTH}, "DATEDIF": {"category": "Date", "signature": "DATEDIF(start_date, end_date, unit)", "description": "Returns elapsed calendar years, months or days.", "contexts": _BOTH}, "IRR": {"category": "Math", "signature": "IRR(values, [guess])", "description": "Returns the periodic internal rate of return near a starting guess.", "contexts": _SHEET}, "XIRR": {"category": "Math", "signature": "XIRR(values, dates, [guess])", "description": "Returns the annual internal rate of return for dated cash flows.", "contexts": _SHEET}, "NORM.DIST": {"category": "Statistical", "signature": "NORM.DIST(x, mean, standard_dev, cumulative)", "description": "Returns a normal probability or density.", "contexts": _BOTH}, "BAHTTEXT": {"category": "Text", "signature": "BAHTTEXT(number)", "description": "Spells a monetary amount in Thai baht and satang.", "contexts": _BOTH}, "ADD": {"category": "Math", "signature": "ADD(value1, value2)", "description": "Adds two values.", "contexts": _BOTH}, "MULTIPLY": {"category": "Math", "signature": "MULTIPLY(value1, value2)", "description": "Multiplies two values.", "contexts": _BOTH}, "FILTER": {"category": "Lookup", "signature": "FILTER(array, include, [if_empty])", "description": "Returns the rows or columns that meet a condition.", "contexts": _SHEET}, "SORT": {"category": "Lookup", "signature": "SORT(array, [sort_index], [sort_order], [by_col])", "description": "Returns an array sorted by a row or column.", "contexts": _SHEET}, "OFFSET": {"category": "Lookup", "signature": "OFFSET(reference, rows, cols, [height], [width])", "description": "Returns a reference shifted by a number of rows and columns.", "contexts": _SHEET}, "INDIRECT": {"category": "Lookup", "signature": "INDIRECT(ref_text, [a1])", "description": "Returns the reference named by a text value.", "contexts": _SHEET}, "RAND": {"category": "Math", "signature": "RAND()", "description": "Returns a random number between zero and one.", "contexts": _BOTH}, # ── Math ───────────────────────────────────────────────────────────────────────────────── "ABS": {"category": "Math", "signature": "ABS(number)", "description": "Returns the absolute value of a number.", "contexts": _BOTH}, "ROUND": {"category": "Math", "signature": "ROUND(number, [num_digits])", "description": "Rounds a number to a specified number of digits.", "contexts": _BOTH}, "ROUNDUP": {"category": "Math", "signature": "ROUNDUP(number, [num_digits])", "description": "Rounds a number up, away from zero.", "contexts": _BOTH}, "ROUNDDOWN": {"category": "Math", "signature": "ROUNDDOWN(number, [num_digits])", "description": "Rounds a number down, toward zero.", "contexts": _BOTH}, "INT": {"category": "Math", "signature": "INT(number)", "description": "Rounds a number down to the nearest integer.", "contexts": _BOTH}, "MOD": {"category": "Math", "signature": "MOD(number, divisor)", "description": "Returns the remainder after a number is divided by a divisor.", "contexts": _BOTH}, "SQRT": {"category": "Math", "signature": "SQRT(number)", "description": "Returns the positive square root of a number.", "contexts": _BOTH}, "POWER": {"category": "Math", "signature": "POWER(number, power)", "description": "Returns the result of a number raised to a power.", "contexts": _BOTH}, "EXP": {"category": "Math", "signature": "EXP(number)", "description": "Returns e raised to the power of a given number.", "contexts": _BOTH}, "LN": {"category": "Math", "signature": "LN(number)", "description": "Returns the natural logarithm of a number.", "contexts": _BOTH}, "SUM": {"category": "Math", "signature": "SUM(number1, [number2], ...)", "description": "Adds all the numbers in a list of values.", "contexts": _BOTH}, # ── Statistical ────────────────────────────────────────────────────────────────────────── "AVERAGE": {"category": "Statistical", "signature": "AVERAGE(number1, [number2], ...)", "description": "Returns the average of its arguments.", "contexts": _BOTH}, "COUNT": {"category": "Statistical", "signature": "COUNT(value1, [value2], ...)", "description": "Counts how many numbers are in a list of values.", "contexts": _BOTH}, "COUNTA": {"category": "Statistical", "signature": "COUNTA(value1, [value2], ...)", "description": "Counts how many values in a list are not empty.", "contexts": _BOTH}, "MIN": {"category": "Statistical", "signature": "MIN(number1, [number2], ...)", "description": "Returns the smallest number in a list of values.", "contexts": _BOTH}, "MAX": {"category": "Statistical", "signature": "MAX(number1, [number2], ...)", "description": "Returns the largest number in a list of values.", "contexts": _BOTH}, # ── Logical ────────────────────────────────────────────────────────────────────────────── "IF": {"category": "Logical", "signature": "IF(logical_test, value_if_true, [value_if_false])", "description": "Returns one value if a condition is TRUE and another value if it is " "FALSE.", "contexts": _BOTH}, "AND": {"category": "Logical", "signature": "AND(logical1, [logical2], ...)", "description": "Returns TRUE only if every one of its arguments is TRUE.", "contexts": _BOTH}, "OR": {"category": "Logical", "signature": "OR(logical1, [logical2], ...)", "description": "Returns TRUE if any one of its arguments is TRUE.", "contexts": _BOTH}, "NOT": {"category": "Logical", "signature": "NOT(logical)", "description": "Reverses the logic of its argument.", "contexts": _BOTH}, "IFERROR": {"category": "Logical", "signature": "IFERROR(value, value_if_error)", "description": "Returns a value you supply if the formula produces an error, and " "the formula result otherwise.", "contexts": _BOTH}, "SWITCH": {"category": "Logical", "signature": "SWITCH(expression, value1, result1, [value2, result2], [default])", "description": "Compares one expression against a list of values and returns the " "result that matches.", "contexts": _BOTH}, # ── Information ────────────────────────────────────────────────────────────────────────── "ISBLANK": {"category": "Information", "signature": "ISBLANK(value)", "description": "Returns TRUE when a value is empty.", "contexts": _BOTH}, # ── Text ───────────────────────────────────────────────────────────────────────────────── "CONCATENATE": {"category": "Text", "signature": "CONCATENATE(text1, [text2], ...)", "description": "Joins several text values into one piece of text.", "contexts": _BOTH}, "LEFT": {"category": "Text", "signature": "LEFT(text, [num_chars])", "description": "Returns the leftmost characters of a text value.", "contexts": _BOTH}, "RIGHT": {"category": "Text", "signature": "RIGHT(text, [num_chars])", "description": "Returns the rightmost characters of a text value.", "contexts": _BOTH}, "MID": {"category": "Text", "signature": "MID(text, start_num, num_chars)", "description": "Returns a specific number of characters from a text value, starting " "at the position you name.", "contexts": _BOTH}, "LEN": {"category": "Text", "signature": "LEN(text)", "description": "Returns the number of characters in a text value.", "contexts": _BOTH}, "TRIM": {"category": "Text", "signature": "TRIM(text)", "description": "Removes extra spaces from a text value.", "contexts": _BOTH}, "UPPER": {"category": "Text", "signature": "UPPER(text)", "description": "Converts a text value to uppercase.", "contexts": _BOTH}, "LOWER": {"category": "Text", "signature": "LOWER(text)", "description": "Converts a text value to lowercase.", "contexts": _BOTH}, "PROPER": {"category": "Text", "signature": "PROPER(text)", "description": "Capitalizes the first letter of each word in a text value.", "contexts": _BOTH}, "VALUE": {"category": "Text", "signature": "VALUE(text)", "description": "Converts a text value that looks like a number into a number.", "contexts": _BOTH}, "TEXT": {"category": "Text", "signature": "TEXT(value, format_text)", "description": "Formats a number and converts it to text.", "contexts": _BOTH}, "SUBSTITUTE": {"category": "Text", "signature": "SUBSTITUTE(text, old_text, new_text, [instance_num])", "description": "Replaces old text with new text in a text value.", "contexts": _BOTH}, "FIND": {"category": "Text", "signature": "FIND(find_text, within_text, [start_num])", "description": "Returns the position of one text value inside another, matching " "case.", "contexts": _BOTH}, "REGEX_EXTRACT": {"category": "Text", "signature": "REGEX_EXTRACT(text, pattern)", "description": "Returns the first part of a text value that matches a " "regular expression.", "contexts": _BOTH}, "REGEX_REPLACE": {"category": "Text", "signature": "REGEX_REPLACE(text, pattern, replacement)", "description": "Replaces every part of a text value that matches a regular " "expression.", "contexts": _BOTH}, # ── Date ───────────────────────────────────────────────────────────────────────────────── "TODAY": {"category": "Date", "signature": "TODAY()", "description": "Returns today's date.", "contexts": _BOTH}, "YEAR": {"category": "Date", "signature": "YEAR(date)", "description": "Returns the year of a date.", "contexts": _BOTH}, "MONTH": {"category": "Date", "signature": "MONTH(date)", "description": "Returns the month of a date, as a number from 1 to 12.", "contexts": _BOTH}, "DAY": {"category": "Date", "signature": "DAY(date)", "description": "Returns the day of the month for a date.", "contexts": _BOTH}, "DAYS": {"category": "Date", "signature": "DAYS(end_date, start_date)", "description": "Returns the number of days between two dates.", "contexts": _BOTH}, "DATEADD": {"category": "Date", "signature": "DATEADD(date, count, units)", "description": "Adds a number of units to a date and returns the new date.", "contexts": _BOTH}, "DATETIME_DIFF": {"category": "Date", "signature": "DATETIME_DIFF(date1, date2, [units])", "description": "Returns the difference between two dates in the units you " "name.", "contexts": _BOTH}, "DATETIME_FORMAT": {"category": "Date", "signature": "DATETIME_FORMAT(date, format)", "description": "Formats a date using the pattern you supply.", "contexts": _BOTH}, # ══ wave 50, W50-T16: the Excel core ═════════════════════════════════════════════════════ # ── Math ───────────────────────────────────────────────────────────────────────────────── "SUMIF": {"category": "Math", "signature": "SUMIF(range, criteria, [sum_range])", "description": "Adds the cells that meet a condition, taking the values from " "sum_range when that last argument is supplied.", "contexts": _SHEET}, "SUMIFS": {"category": "Math", "signature": "SUMIFS(sum_range, criteria_range1, criteria1, ...)", "description": "Adds the cells in sum_range, the FIRST argument, that meet every " "one of several conditions.", "contexts": _SHEET}, "SUMPRODUCT": {"category": "Math", "signature": "SUMPRODUCT(array1, [array2], ...)", "description": "Multiplies matching cells in the ranges you name and returns " "the sum of those products.", "contexts": _SHEET}, "CEILING": {"category": "Math", "signature": "CEILING(number, significance)", "description": "Rounds a number up to the nearest multiple of significance.", "contexts": _BOTH}, "FLOOR": {"category": "Math", "signature": "FLOOR(number, significance)", "description": "Rounds a number down to the nearest multiple of significance.", "contexts": _BOTH}, "MROUND": {"category": "Math", "signature": "MROUND(number, multiple)", "description": "Rounds a number to the nearest multiple you name.", "contexts": _BOTH}, "PRODUCT": {"category": "Math", "signature": "PRODUCT(number1, [number2], ...)", "description": "Multiplies all the numbers in a list of values.", "contexts": _BOTH}, # ── Statistical ────────────────────────────────────────────────────────────────────────── "COUNTIF": {"category": "Statistical", "signature": "COUNTIF(range, criteria)", "description": "Counts the cells in a range that meet a condition.", "contexts": _SHEET}, "COUNTIFS": {"category": "Statistical", "signature": "COUNTIFS(criteria_range1, criteria1, ...)", "description": "Counts the cells that meet every one of several conditions.", "contexts": _SHEET}, "AVERAGEIF": {"category": "Statistical", "signature": "AVERAGEIF(range, criteria, [average_range])", "description": "Returns the average of the cells that meet a condition, taking " "the values from average_range when that last argument is " "supplied.", "contexts": _SHEET}, "AVERAGEIFS": {"category": "Statistical", "signature": "AVERAGEIFS(average_range, criteria_range1, criteria1, ...)", "description": "Returns the average of the cells in average_range, the FIRST " "argument, that meet every one of several conditions.", "contexts": _SHEET}, "MAXIFS": {"category": "Statistical", "signature": "MAXIFS(max_range, criteria_range1, criteria1, ...)", "description": "Returns the largest number among the cells that meet every one of " "several conditions.", "contexts": _SHEET}, "MINIFS": {"category": "Statistical", "signature": "MINIFS(min_range, criteria_range1, criteria1, ...)", "description": "Returns the smallest number among the cells that meet every one of " "several conditions.", "contexts": _SHEET}, "RANK": {"category": "Statistical", "signature": "RANK(number, ref, [order])", "description": "Returns the position of a number in a range, largest first unless " "you pass a non zero order.", "contexts": _SHEET}, "MEDIAN": {"category": "Statistical", "signature": "MEDIAN(number1, [number2], ...)", "description": "Returns the middle number in a list of values.", "contexts": _BOTH}, "STDEV": {"category": "Statistical", "signature": "STDEV(number1, [number2], ...)", "description": "Estimates the standard deviation of a population from a sample of " "it.", "contexts": _BOTH}, "STDEV.P": {"category": "Statistical", "signature": "STDEV.P(number1, [number2], ...)", "description": "Returns the standard deviation of a whole population.", "contexts": _BOTH}, "VAR": {"category": "Statistical", "signature": "VAR(number1, [number2], ...)", "description": "Estimates the variance of a population from a sample of it.", "contexts": _BOTH}, "VAR.P": {"category": "Statistical", "signature": "VAR.P(number1, [number2], ...)", "description": "Returns the variance of a whole population.", "contexts": _BOTH}, "PERCENTILE": {"category": "Statistical", "signature": "PERCENTILE(array, k)", "description": "Returns the value below which the fraction k of a range falls, " "interpolating between neighbours.", "contexts": _SHEET}, "QUARTILE": {"category": "Statistical", "signature": "QUARTILE(array, quart)", "description": "Returns a quartile of a range, where quart runs from 0 for the " "smallest value to 4 for the largest.", "contexts": _SHEET}, "LARGE": {"category": "Statistical", "signature": "LARGE(array, k)", "description": "Returns the k-th largest number in a range.", "contexts": _SHEET}, "SMALL": {"category": "Statistical", "signature": "SMALL(array, k)", "description": "Returns the k-th smallest number in a range.", "contexts": _SHEET}, "COUNTBLANK": {"category": "Statistical", "signature": "COUNTBLANK(range)", "description": "Counts the empty cells in a range.", "contexts": _SHEET}, "AVERAGEA": {"category": "Statistical", "signature": "AVERAGEA(value1, [value2], ...)", "description": "Returns the average of its arguments, counting text as zero.", "contexts": _BOTH}, # ── Logical ────────────────────────────────────────────────────────────────────────────── "IFS": {"category": "Logical", "signature": "IFS(logical_test1, value1, [logical_test2, value2], ...)", "description": "Checks conditions in order and returns the value beside the first one " "that is TRUE.", "contexts": _BOTH}, "IFNA": {"category": "Logical", "signature": "IFNA(value, value_if_na)", "description": "Returns a value you supply when a formula finds no match, and the " "formula result otherwise.", "contexts": _BOTH}, "XOR": {"category": "Logical", "signature": "XOR(logical1, [logical2], ...)", "description": "Returns TRUE when an odd number of its arguments are TRUE.", "contexts": _BOTH}, # ── Text ───────────────────────────────────────────────────────────────────────────────── "TEXTJOIN": {"category": "Text", "signature": "TEXTJOIN(delimiter, ignore_empty, text1, [text2], ...)", "description": "Joins text values with a delimiter between them, optionally " "skipping the empty ones.", "contexts": _BOTH}, "REPT": {"category": "Text", "signature": "REPT(text, number_times)", "description": "Repeats a text value the number of times you name.", "contexts": _BOTH}, "EXACT": {"category": "Text", "signature": "EXACT(text1, text2)", "description": "Returns TRUE when two text values are identical, matching case.", "contexts": _BOTH}, # ── Date ───────────────────────────────────────────────────────────────────────────────── "DATE": {"category": "Date", "signature": "DATE(year, month, day)", "description": "Builds a date from a year, a month and a day.", "contexts": _BOTH}, "DATEVALUE": {"category": "Date", "signature": "DATEVALUE(date_text)", "description": "Reads a date written as text and returns it as a date.", "contexts": _BOTH}, "NOW": {"category": "Date", "signature": "NOW()", "description": "Returns the current date and time.", "contexts": _BOTH}, "HOUR": {"category": "Date", "signature": "HOUR(time)", "description": "Returns the hour of a time, as a number from 0 to 23.", "contexts": _BOTH}, "MINUTE": {"category": "Date", "signature": "MINUTE(time)", "description": "Returns the minute of a time, as a number from 0 to 59.", "contexts": _BOTH}, "EOMONTH": {"category": "Date", "signature": "EOMONTH(date, months)", "description": "Returns the last day of the month a number of months away from a " "date.", "contexts": _BOTH}, "EDATE": {"category": "Date", "signature": "EDATE(date, months)", "description": "Returns the date a number of months away from a date.", "contexts": _BOTH}, "WEEKDAY": {"category": "Date", "signature": "WEEKDAY(date, [return_type])", "description": "Returns the day of the week of a date as a number.", "contexts": _BOTH}, "WEEKNUM": {"category": "Date", "signature": "WEEKNUM(date, [return_type])", "description": "Returns the week of the year a date falls in.", "contexts": _BOTH}, "NETWORKDAYS": {"category": "Date", "signature": "NETWORKDAYS(start_date, end_date, [holidays])", "description": "Counts the working days between two dates, skipping weekends " "and any holidays you name.", "contexts": _BOTH}, "WORKDAY": {"category": "Date", "signature": "WORKDAY(start_date, days, [holidays])", "description": "Returns the date a number of working days away from a date, " "skipping weekends and any holidays you name.", "contexts": _BOTH}, # ── Lookup ─────────────────────────────────────────────────────────────────────────────── "VLOOKUP": {"category": "Lookup", "signature": "VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])", "description": "Finds a value in the first column of a range and returns a value " "from the same row, matching approximately unless range_lookup is " "FALSE.", "contexts": _SHEET}, "HLOOKUP": {"category": "Lookup", "signature": "HLOOKUP(lookup_value, table_array, row_index_num, [range_lookup])", "description": "Finds a value in the first row of a range and returns a value " "from the same column, matching approximately unless range_lookup " "is FALSE.", "contexts": _SHEET}, "XLOOKUP": {"category": "Lookup", "signature": "XLOOKUP(lookup_value, lookup_array, return_array, [if_not_found], [match_mode])", "description": "Finds a value in one range and returns the matching value from " "another, with an answer of your own when nothing matches.", "contexts": _SHEET}, "INDEX": {"category": "Lookup", "signature": "INDEX(array, row_num, [column_num])", "description": "Returns the value at a position in a range.", "contexts": _SHEET}, "MATCH": {"category": "Lookup", "signature": "MATCH(lookup_value, lookup_array, [match_type])", "description": "Returns the position of a value in a range.", "contexts": _SHEET}, "CHOOSE": {"category": "Lookup", "signature": "CHOOSE(index_num, value1, [value2], ...)", "description": "Returns the value at the position you name in a list.", "contexts": _BOTH}, "ROW": {"category": "Lookup", "signature": "ROW([reference])", "description": "Returns the row number of a cell, or of this cell when you name none.", "contexts": _SHEET}, "COLUMN": {"category": "Lookup", "signature": "COLUMN([reference])", "description": "Returns the column number of a cell, or of this cell when you name " "none.", "contexts": _SHEET}, "ROWS": {"category": "Lookup", "signature": "ROWS(array)", "description": "Returns the number of rows in a range.", "contexts": _SHEET}, "COLUMNS": {"category": "Lookup", "signature": "COLUMNS(array)", "description": "Returns the number of columns in a range.", "contexts": _SHEET}, # ── Information ────────────────────────────────────────────────────────────────────────── "ISNUMBER": {"category": "Information", "signature": "ISNUMBER(value)", "description": "Returns TRUE when a value is a number.", "contexts": _BOTH}, "ISTEXT": {"category": "Information", "signature": "ISTEXT(value)", "description": "Returns TRUE when a value is text.", "contexts": _BOTH}, "ISERROR": {"category": "Information", "signature": "ISERROR(value)", "description": "Returns TRUE when a formula would refuse to produce a value.", "contexts": _BOTH}, } #: What the catalogue route publishes as `fieldRef`: the spelling a consumer shows a user when it #: explains how to name a field inside a formula. One constant so the editor's placeholder, the #: Sheet's help and the grammar cannot disagree about the braces. FIELD_REF = "{key}" def catalogue_rows(): """The C2 `functions` list: one row per catalogued function, in catalogue order. Arity is read from `FN_ARITY` (see the note above `FN_CATALOGUE`) and `aliases` is the INVERSE of `ALIASES`, so a consumer offering autocomplete can show that `CONCAT` types the same function as `CONCATENATE` without parsing the alias map itself. """ inverse = {} for spelling, canonical in ALIASES.items(): inverse.setdefault(canonical, []).append(spelling) rows = [] for name, entry in FN_CATALOGUE.items(): low, high = FN_ARITY[name] rows.append({"name": name, "category": entry["category"], "signature": entry["signature"], "description": entry["description"], "minArgs": low, "maxArgs": high, "contexts": list(entry["contexts"]), "aliases": sorted(inverse.get(name, ()))}) return rows # Every accepted source token has a fixture. The AST stores the canonical token (``=`` and # ``!=``), while the grammar publishes the spelling aliases so a browser never has to infer them. OPERATOR_PARITY_FIXTURES = { "neg": ("-5", {}, -5.0), "add": ("{a} + {b}", {"a": 2, "b": 3}, 5.0), "subtract": ("{a} - {b}", {"a": 7, "b": 2}, 5.0), "multiply": ("{a} * {b}", {"a": 3, "b": 4}, 12.0), "divide": ("{a} / {b}", {"a": 9, "b": 3}, 3.0), "power": ("{a} ^ {b}", {"a": 2, "b": 3}, 8.0), "concatenate": ("{a} & {b}", {"a": "A", "b": "B"}, "AB"), "less_than": ("{a} < {b}", {"a": 2, "b": 3}, "TRUE"), "less_or_equal": ("{a} <= {b}", {"a": 3, "b": 3}, "TRUE"), "greater_than": ("{a} > {b}", {"a": 4, "b": 3}, "TRUE"), "greater_or_equal": ("{a} >= {b}", {"a": 3, "b": 3}, "TRUE"), "equal": ("{a} = {b}", {"a": "A", "b": "a"}, "TRUE"), "equal_alias": ("{a} == {b}", {"a": 3, "b": 3}, "TRUE"), "not_equal": ("{a} != {b}", {"a": 2, "b": 3}, "TRUE"), "not_equal_alias": ("{a} <> {b}", {"a": 2, "b": 3}, "TRUE"), } PARSE_ERROR_FIXTURES = { "empty": "", "legacy_square_reference": "[amount] + 1", "unknown_function": "UNKNOWN(1)", "wrong_arity": "ABS(1, 2)", "unclosed_reference": "{amount + 1", "invalid_reference": "{amount-due} + 1", "unterminated_text": '"amount', "chained_comparison": "1 < 2 < 3", "unsupported_operator": "5 % 2", } EVALUATION_ERROR_FIXTURES = { "unknown_ref": ("{missing} + 1", {}, "unknown_ref"), "div_zero": ("{amount} / 0", {"amount": 4}, "div_zero"), } # Shared contract fixture corpus. The API publishes this exact data so the browser preview gate # can evaluate the same source/row/today triples without maintaining a second handwritten grammar. PARITY_FIXTURES = { "FV": ("FV(0,2,10,100)", -120), "DATEDIF": ('DATEDIF("2001-06-01","2002-08-15","D")', 440), "IRR": ("IRR(B2:B3)", 0.1), "XIRR": ("XIRR(B2:B3,C2:C3)", 0.1), "NORM.DIST": ("NORM.DIST(0,0,1,TRUE)", 0.5), "BAHTTEXT": ("BAHTTEXT(21)", "ยี่สิบเอ็ดบาทถ้วน"), "ADD": ("ADD(4,7)", 11), "MULTIPLY": ("MULTIPLY(4,7)", 28), "FILTER": ("SUM(FILTER(3,TRUE))", 3), "SORT": ("SUM(SORT(3))", 3), "OFFSET": ("OFFSET(B2, 1, 1)", 20), "INDIRECT": ('INDIRECT("B2")', 1), "RAND": ("RAND()>=0", "TRUE"), "ABS": ("ABS(-2)", 2.0), "ROUND": ("ROUND(2.345, 2)", 2.35), "ROUNDUP": ("ROUNDUP(2.341, 2)", 2.35), "ROUNDDOWN": ("ROUNDDOWN(2.349, 2)", 2.34), "INT": ("INT(2.9)", 2), "MOD": ("MOD(7, 4)", 3.0), "SQRT": ("SQRT(9)", 3.0), "POWER": ("POWER(2, 3)", 8.0), "EXP": ("EXP(0)", 1.0), "LN": ("LN(1)", 0.0), "SUM": ("SUM(1, 2, 3)", 6.0), "AVERAGE": ("AVERAGE(2, 4)", 3.0), "COUNT": ("COUNT(1, \"x\", 3)", 2), "COUNTA": ("COUNTA(1, \"x\", \"\")", 2), "MIN": ("MIN(4, 2)", 2.0), "MAX": ("MAX(4, 2)", 4.0), "IF": ("IF(TRUE, 1, 2)", 1), "AND": ("AND(TRUE, TRUE)", "TRUE"), "OR": ("OR(FALSE, TRUE)", "TRUE"), "NOT": ("NOT(FALSE)", "TRUE"), "IFERROR": ("IFERROR(1 / 0, 7)", 7), "ISBLANK": ("ISBLANK({empty})", "TRUE"), "SWITCH": ("SWITCH(\"A\", \"A\", 1, 0)", 1), "CONCATENATE": ("CONCATENATE(\"A\", \"B\")", "AB"), "LEFT": ("LEFT(\"ABC\", 2)", "AB"), "RIGHT": ("RIGHT(\"ABC\", 2)", "BC"), "MID": ("MID(\"ABCD\", 2, 2)", "BC"), "LEN": ("LEN(\"ABC\")", 3), "TRIM": ("TRIM(\" A B \" )", "A B"), "UPPER": ("UPPER(\"Ab\")", "AB"), "LOWER": ("LOWER(\"Ab\")", "ab"), "PROPER": ("PROPER(\"hello world\")", "Hello World"), "VALUE": ("VALUE(\"12.5\")", 12.5), "TEXT": ("TEXT(0.25, \"0%\")", "25%"), "SUBSTITUTE": ("SUBSTITUTE(\"a-b\", \"-\", \"+\")", "a+b"), "FIND": ("FIND(\"b\", \"abc\")", 2), "REGEX_EXTRACT": ("REGEX_EXTRACT(\"SO-42\", \"SO-[0-9]+\")", "SO-42"), "REGEX_REPLACE": ("REGEX_REPLACE(\"SO-42\", \"[0-9]+\", \"#\")", "SO-#"), "TODAY": ("TODAY()", "2024-01-02"), "YEAR": ("YEAR(\"2024-01-02\")", 2024), "MONTH": ("MONTH(\"2024-01-02\")", 1), "DAY": ("DAY(\"2024-01-02\")", 2), "DAYS": ("DAYS(\"2024-01-05\", \"2024-01-02\")", 3), "DATEADD": ("DATEADD(\"2024-01-31\", 1, \"months\")", "2024-02-29"), "DATETIME_DIFF": ("DATETIME_DIFF(\"2024-01-16\", \"2024-01-02\", \"weeks\")", 2), "DATETIME_FORMAT": ("DATETIME_FORMAT(\"2024-01-02\", \"YYYY-MM-DD\")", "2024-01-02"), # ══ wave 50, W50-T16 ═════════════════════════════════════════════════════════════════════ # A fixture whose source names a RANGE needs cells to read; those live in `PARITY_ROWS` # below, keyed by the same function name. The tuple shape here is unchanged on purpose: # `contract_dto()` unpacks exactly `(source, expected)`. "SUMIF": ("SUMIF(B2:B6, \">2\", C2:C6)", 120.0), "SUMIFS": ("SUMIFS(C2:C6, B2:B6, \">2\")", 120.0), "COUNTIF": ("COUNTIF(B2:B6, \">2\")", 3), "COUNTIFS": ("COUNTIFS(B2:B6, \">2\", C2:C6, \"<50\")", 2), "AVERAGEIF": ("AVERAGEIF(B2:B6, \">2\", C2:C6)", 40.0), "AVERAGEIFS": ("AVERAGEIFS(C2:C6, B2:B6, \">2\")", 40.0), "MAXIFS": ("MAXIFS(C2:C6, B2:B6, \">2\")", 50.0), "MINIFS": ("MINIFS(C2:C6, B2:B6, \">2\")", 30.0), "SUMPRODUCT": ("SUMPRODUCT(B2:B4, C2:C4)", 140.0), "VLOOKUP": ("VLOOKUP(3, B2:C6, 2, FALSE)", 30), "HLOOKUP": ("HLOOKUP(3, B2:E3, 2, FALSE)", 30), "XLOOKUP": ("XLOOKUP(3, B2:B6, C2:C6, \"none\")", 30), "INDEX": ("INDEX(B2:C6, 3, 2)", 30), "MATCH": ("MATCH(3, B2:B6, 0)", 3), "CHOOSE": ("CHOOSE(2, \"a\", \"b\", \"c\")", "b"), "ROW": ("ROW(B4)", 4), "COLUMN": ("COLUMN(C2)", 3), "ROWS": ("ROWS(B2:C6)", 5), "COLUMNS": ("COLUMNS(B2:C6)", 2), "IFS": ("IFS(FALSE, 1, TRUE, 2)", 2), "IFNA": ("IFNA(1, 2)", 1), "XOR": ("XOR(TRUE, FALSE)", "TRUE"), "RANK": ("RANK(3, B2:B6)", 3), "MEDIAN": ("MEDIAN(1, 2, 3, 4)", 2.5), "STDEV": ("STDEV(1, 1, 4, 7, 7)", 3.0), "STDEV.P": ("STDEV.P(2, 4, 4, 4, 5, 5, 7, 9)", 2.0), "VAR": ("VAR(1, 1, 4, 7, 7)", 9.0), "VAR.P": ("VAR.P(1, 1, 4, 7, 7)", 7.2), "PERCENTILE": ("PERCENTILE(B2:B6, 0.25)", 2.0), "QUARTILE": ("QUARTILE(B2:B6, 1)", 2.0), "LARGE": ("LARGE(B2:B6, 2)", 4.0), "SMALL": ("SMALL(B2:B6, 2)", 2.0), "COUNTBLANK": ("COUNTBLANK(B2:B6)", 2), "AVERAGEA": ("AVERAGEA(1, \"x\", 5)", 2.0), "CEILING": ("CEILING(2.1, 0.5)", 2.5), "FLOOR": ("FLOOR(2.9, 0.5)", 2.5), "MROUND": ("MROUND(7, 3)", 6.0), "PRODUCT": ("PRODUCT(2, 3, 4)", 24.0), "EOMONTH": ("EOMONTH(\"2024-01-15\", 1)", "2024-02-29"), "EDATE": ("EDATE(\"2024-01-31\", 1)", "2024-02-29"), "WEEKDAY": ("WEEKDAY(\"2024-01-02\")", 3), "WEEKNUM": ("WEEKNUM(\"2024-01-07\", 1)", 2), "NETWORKDAYS": ("NETWORKDAYS(\"2024-01-01\", \"2024-01-07\")", 5), "WORKDAY": ("WORKDAY(\"2024-01-01\", 5)", "2024-01-08"), "DATE": ("DATE(2024, 1, 2)", "2024-01-02"), "DATEVALUE": ("DATEVALUE(\"2024-01-02\")", "2024-01-02"), "NOW": ("NOW()", "2024-01-02 00:00:00"), "HOUR": ("HOUR(\"2024-01-02 13:45:00\")", 13), "MINUTE": ("MINUTE(\"2024-01-02 13:45:00\")", 45), "TEXTJOIN": ("TEXTJOIN(\"-\", TRUE, \"A\", \"\", \"B\")", "A-B"), "REPT": ("REPT(\"ab\", 3)", "ababab"), "EXACT": ("EXACT(\"A\", \"a\")", "FALSE"), "ISNUMBER": ("ISNUMBER(1)", "TRUE"), "ISTEXT": ("ISTEXT(\"a\")", "TRUE"), "ISERROR": ("ISERROR(1 / 0)", "TRUE"), } #: One rectangle, reused by most range fixtures: B2:B6 holds 1 to 5 and C2:C6 holds 10 to 50. #: ⛔ KEYS ARE EXACTLY WHAT `a1_key` EMITS: upper case, no `$`. A lower-case key does not fail #: loudly; it simply never matches, so a splice path answers `unknown_ref` and a range path reads #: a blank, and the fixture then fails with a got/want that points nowhere near the real cause. _CELLS_BC = {"B2": 1, "B3": 2, "B4": 3, "B5": 4, "B6": 5, "C2": 10, "C3": 20, "C4": 30, "C5": 40, "C6": 50} #: ⭐ CELLS FOR A RANGE FIXTURE, AND A SEPARATE TABLE ON PURPOSE (W50-T16). #: #: `PARITY_FIXTURES` is `{name: (source, expected)}` and `contract_dto()` unpacks exactly that #: 2-tuple, so widening it to carry cells would break the published contract for all 46 shipped #: functions. This table is consulted BESIDE it by whatever drives the corpus, defaulting to #: `{"empty": None}` for a function whose fixture names no cell. #: #: ⚠ IT IS DELIBERATELY NOT WIRED INTO `contract_dto()`, which still publishes the hardcoded #: `"row": {"empty": None}` for every fixture. A consumer that runs the PUBLISHED corpus therefore #: cannot reproduce a range fixture from the DTO alone and must read this table. PARITY_ROWS = { "IRR": {"B2": -100, "B3": 110}, "XIRR": {"B2": -100, "B3": 110, "C2": "2021-01-01", "C3": "2022-01-01"}, "OFFSET": _CELLS_BC, "INDIRECT": _CELLS_BC, "SUMIF": _CELLS_BC, "SUMIFS": _CELLS_BC, "COUNTIF": _CELLS_BC, "COUNTIFS": _CELLS_BC, "AVERAGEIF": _CELLS_BC, "AVERAGEIFS": _CELLS_BC, "MAXIFS": _CELLS_BC, "MINIFS": _CELLS_BC, "SUMPRODUCT": _CELLS_BC, "VLOOKUP": _CELLS_BC, "XLOOKUP": _CELLS_BC, "INDEX": _CELLS_BC, "MATCH": _CELLS_BC, "RANK": _CELLS_BC, "PERCENTILE": _CELLS_BC, "QUARTILE": _CELLS_BC, "LARGE": _CELLS_BC, "SMALL": _CELLS_BC, "HLOOKUP": {"B2": 1, "C2": 2, "D2": 3, "E2": 4, "B3": 10, "C3": 20, "D3": 30, "E3": 40}, "COUNTBLANK": {"B2": 1, "B3": "", "B4": 3, "B6": 5}, } #: ⭐ THE BOUNDARY CASES, PINNED RATHER THAN IMPLIED (W50-T16). #: #: `PARITY_FIXTURES` carries exactly one example per function name, which is what makes its key set #: comparable with `FN_ARITY` and `FN_CATALOGUE`. Several of this wave's rules only show up as a #: CONTRAST between two examples: SUMIF's sum range last against SUMIFS's first, VLOOKUP's #: approximate default against its exact fourth argument, EXACT's case sensitivity against `=`, #: and above all the text rule (a range member ignores text; a scalar numeric argument refuses). #: Those pairs live here as `(source, row, expected_value, expected_error)`. PARITY_VARIANTS = { # ⛔ THE ARGUMENT-ORDER CONTRAST. Both answer 120 over the same cells; an implementation that # has the two ranges the wrong way round answers 15 for both, which is why they are here as a # pair rather than trusted one at a time. "sumif_sum_range_last": ("SUMIF(B2:B6, \">2\", C2:C6)", _CELLS_BC, 120.0, None), "sumifs_sum_range_first": ("SUMIFS(C2:C6, B2:B6, \">2\")", _CELLS_BC, 120.0, None), "sumif_no_sum_range": ("SUMIF(B2:B6, \">2\")", _CELLS_BC, 12.0, None), # VLOOKUP's fourth argument defaults to TRUE, which is approximate. Both branches, so the # default cannot silently become the strict one or the other way round. "vlookup_approximate_default": ("VLOOKUP(3.5, B2:C6, 2)", _CELLS_BC, 30, None), "vlookup_exact_refuses": ("VLOOKUP(3.5, B2:C6, 2, FALSE)", _CELLS_BC, None, "no_match"), "xlookup_if_not_found": ("XLOOKUP(9, B2:B6, C2:C6, \"none\")", _CELLS_BC, "none", None), "match_approximate": ("MATCH(3.5, B2:B6, 1)", _CELLS_BC, 3, None), "ifna_catches_no_match": ("IFNA(MATCH(9, B2:B6, 0), \"none\")", _CELLS_BC, "none", None), # The shape work. A flat list of values cannot answer either of these. "rows_of_a_rectangle": ("ROWS(B2:C6)", {}, 5, None), "columns_of_a_rectangle": ("COLUMNS(B2:C6)", {}, 2, None), "row_of_this_cell": ("ROW()", {"!ADDR": "B7"}, 7, None), "row_without_an_address": ("ROW()", {}, None, "bad_value"), # Criteria forms. "criteria_wildcard": ("COUNTIF(D2:D5, \"a*\")", {"D2": "apple", "D3": "banana", "D4": "avocado", "D5": "cherry"}, 2, None), "criteria_text_ignores_case": ("COUNTIF(D2:D5, \"APPLE\")", {"D2": "apple", "D3": "banana", "D4": "avocado", "D5": "cherry"}, 1, None), "criteria_length_mismatch": ("SUMIF(B2:B6, \">2\", C2:C4)", _CELLS_BC, None, "bad_value"), # ⛔ THE TEXT RULE, BOTH SIDES. A range member ignores text, because that is Excel and because # `COUNT` and `COUNTA` have shipped fixtures that depend on it. A SCALAR numeric argument to a # wave-50 function refuses instead, because silently reading text as blank there would answer # a plausible number to a question nobody asked. "count_still_ignores_text": ("COUNT(1, \"x\", 3)", {}, 2, None), "sum_over_range_ignores_text": ("SUM(B2:B4)", {"B2": 1, "B3": "x", "B4": 3}, 4.0, None), "average_over_range_ignores_blank": ("AVERAGE(B2:B4)", {"B2": 1, "B3": None, "B4": 3}, 2.0, None), "scalar_text_refuses": ("CEILING(\"x\", 2)", {}, None, "bad_value"), "scalar_text_refuses_in_large": ("LARGE(B2:B6, \"x\")", _CELLS_BC, None, "bad_value"), # EXACT matches case, `=` does not. "exact_matches_case": ("EXACT(\"A\", \"a\")", {}, "FALSE", None), "equals_ignores_case": ("\"A\" = \"a\"", {}, "TRUE", None), # WEEKNUM's two return types disagree about the same Sunday. "weeknum_week_begins_sunday": ("WEEKNUM(\"2024-01-07\", 1)", {}, 2, None), "weeknum_week_begins_monday": ("WEEKNUM(\"2024-01-07\", 2)", {}, 1, None), "networkdays_with_holidays": ("NETWORKDAYS(\"2024-01-01\", \"2024-01-07\", B2:B2)", {"B2": "2024-01-03"}, 4, None), # The dotted Excel spellings, which are not valid Python call syntax. "dotted_stdev_p": ("STDEV.P(2, 4, 4, 4, 5, 5, 7, 9)", {}, 2.0, None), "dotted_var_p": ("VAR.P(1, 1, 4, 7, 7)", {}, 7.2, None), } class FormulaError(ValueError): pass # ── A1 addressing (wave 49, W49-T03, contract C1) ──────────────────────────────────────────── # # ⭐ THE SEAM IS `_rewrite`, AND THAT IS NOT AN ACCIDENT OF CONVENIENCE. `B4`, `B4:B8`, `$B$1` and # `Sheet2!C3` are not valid Python expressions: `:` is subscript-only, `!` is not an operator, and a # bare `B4` parses as `ast.Name`, which `_normal` refuses. So an A1 token is translated to a # synthetic call BEFORE `ast.parse` ever sees it, exactly as `{field}` already becomes `REF('field')`. # One rewrite pass, one grammar, no second parser. # # ⛔⛔ THE COLLISION THAT MAKES THE `(` LOOKAHEAD LOAD-BEARING: a function name can have the SHAPE of # a cell reference. `LOG10` is three letters followed by digits, which is exactly `$?[A-Za-z]{1,3}$? # [0-9]+`. Without the lookahead, `LOG10(x)` rewrites to `A1REF('LOG10')(x)` and the formula either # dies with an unhelpful parse error or, worse, silently resolves a cell nobody wrote. The # disambiguator is the character AFTER the token: a `(` means it is a call, never an address. MAX_A1_ROW = 9_999_999 MAX_A1_COL = 3 # AAA, i.e. well past Excel's XFD #: A range is materialised into a list of values, so it needs a ceiling for the same reason #: `MAX_SOURCE` exists: one cell must not be able to ask for an unbounded amount of work. MAX_RANGE_CELLS = 5000 #: W50-T16. `REPT` and the working-day walk are the two wave-50 functions whose cost is set by an #: ARGUMENT rather than by the formula's own size, so each needs a ceiling of its own for the same #: reason `MAX_SOURCE` exists: one cell must not be able to ask for an unbounded amount of work. MAX_TEXT_RESULT = 10000 MAX_DAY_SPAN = 20000 _A1_CELL = r"\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})" _A1_RE = re.compile( r"(?:(?:'([^']{1,64})'|([A-Za-z_][A-Za-z0-9_]{0,63}))!)?" + _A1_CELL + r"(?::" + _A1_CELL + r")?" ) def col_to_index(letters): """`A` -> 1, `Z` -> 26, `AA` -> 27. The spreadsheet base-26 with no zero digit.""" n = 0 for ch in str(letters).upper(): n = n * 26 + (ord(ch) - 64) return n def index_to_col(index): """The inverse of `col_to_index`. Refuses a non-positive index rather than emitting nonsense.""" n = int(index) if n < 1: raise FormulaError("a column index starts at 1") out = "" while n: n, rem = divmod(n - 1, 26) out = chr(65 + rem) + out return out def a1_key(addr, sheet=""): """The lookup key for one address: `B4`, or `SHEET2!C3` when it names another tab. ⚠ `$` is NOT part of the key. Anchoring belongs to a formula's TEXT, where it changes how a drag-fill shifts the reference; it never changes which cell is being addressed. Keeping it in the key would make `$B$1` and `B1` two different cells. """ plain = str(addr or "").replace("$", "").upper() return (str(sheet).upper() + "!" + plain) if sheet else plain def expand_range(first, last, sheet=""): """Every address in the rectangle `first:last`, row-major, as lookup keys.""" c1, r1 = _split_addr(first) c2, r2 = _split_addr(last) lo_c, hi_c = sorted((col_to_index(c1), col_to_index(c2))) lo_r, hi_r = sorted((r1, r2)) span = (hi_c - lo_c + 1) * (hi_r - lo_r + 1) if span > MAX_RANGE_CELLS: raise FormulaError(f"a range covers at most {MAX_RANGE_CELLS} cells") return [a1_key(index_to_col(c) + str(r), sheet) for r in range(lo_r, hi_r + 1) for c in range(lo_c, hi_c + 1)] def _split_addr(addr): m = re.fullmatch(r"\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})", str(addr or "").strip()) if not m: raise FormulaError(f"{addr} is not a cell address") return m.group(1).upper(), int(m.group(2)) #: ⭐ THE CURRENT CELL'S OWN ADDRESS, CARRIED IN `row` (W50-T16). #: #: `ROW()` and `COLUMN()` with no argument are the only functions here that need to know WHERE they #: are, and `evaluate_sheet` is the only caller that knows. Threading it through `row` rather than #: adding a parameter keeps every other signature in this file unchanged. #: ⛔ `"!ADDR"` CAN COLLIDE WITH NOTHING, AND THAT IS WHY IT LOOKS LIKE THAT. A field key is #: `[A-Za-z0-9_]+`, so no field can be called this; and `a1_key` only emits a `!` when the sheet #: name is non-empty, so no cell address can be either. SHEET_ADDR_KEY = "!ADDR" class Range: """A rectangle of cell values in row-major order, carrying its own shape. ⭐ THE SHAPE IS THE POINT. The wave-49 splice hands a function MORE POSITIONAL ARGUMENTS, which is right for `SUM` and impossible for `ROWS`, `INDEX` or `VLOOKUP`: a flat list cannot say how many rows it had, and a lookup table is meaningless without its columns. `rows` and `cols` always satisfy `rows * cols == len(values)`. """ __slots__ = ("values", "rows", "cols") def __init__(self, values, rows, cols): self.values = list(values) self.rows = int(rows) self.cols = int(cols) if self.rows * self.cols != len(self.values): raise FormulaError("a range shape does not match its cells") def cell(self, r, c): """The value at 1-based row `r`, column `c`, or None outside the rectangle.""" if not (1 <= r <= self.rows and 1 <= c <= self.cols): return None return self.values[(r - 1) * self.cols + (c - 1)] def __iter__(self): return iter(self.values) def __len__(self): return len(self.values) @classmethod def scalar(cls, value): """A single value standing where a range was expected, as Excel allows.""" return cls([value], 1, 1) def _range_shape(keys): """`(rows, cols)` for the bounding box of a list of A1 lookup keys. ⚠ THE `SHEET!` PREFIX IS STRIPPED FIRST. `_split_addr` reads an address only, so a cross-sheet range such as `Sheet2!B2:Sheet2!C6` would otherwise raise while deriving a shape that is perfectly well defined. """ rows, cols = [], [] for key in keys: column, row = _split_addr(str(key).rsplit("!", 1)[-1]) cols.append(col_to_index(column)) rows.append(row) if not rows: raise FormulaError("a range covers no cells") return max(rows) - min(rows) + 1, max(cols) - min(cols) + 1 #: A marker for "every argument of this function is a range", used by SUMPRODUCT. ALL_ARGS = "*" #: ⭐⭐ WHICH ARGUMENT POSITIONS TAKE A SHAPED RANGE, AND THE ABSENCE OF A NAME IS ALSO A DECISION. #: #: A function ABSENT from this table keeps the wave-49 behaviour exactly: an `a1range` argument is #: SPLICED into more positional arguments. That is correct for `SUM`, `AVERAGE`, `COUNT`, `MIN`, #: `MAX`, and equally for `MEDIAN`, `STDEV`, `VAR`, `PRODUCT`, `AVERAGEA` and `CHOOSE`, all of #: which simply iterate a flat argument list. Leaving them out is what keeps all 46 shipped #: functions untouched. #: #: A function PRESENT here receives a `Range` at the positions named and ORDINARY evaluation #: everywhere else. ⛔ IT IS NEVER SPLICED AT A NON-RANGE POSITION, and that is deliberate: these #: functions read meaning off argument POSITION, so a splice that inserted five values where a #: criteria string was expected would shift every later argument and corrupt the very mapping this #: table declares. A range arriving at a scalar position instead evaluates to the honest #: `range_outside_function` refusal. #: #: The value is `(explicit_indices, (start, step) | None)` or `ALL_ARGS`; the second member covers #: a repeating variadic pattern such as SUMIFS's `criteria_range, criteria` pairs. #: #: ⛔ SUMIF PUTS THE SUM RANGE LAST AND SUMIFS PUTS IT FIRST. Reading this table backwards is the #: classic Excel bug, so both spellings carry a fixture over the same cells. RANGE_ARGS = { "IRR": ((0,), None), "XIRR": ((0, 1), None), "FILTER": ((0, 1), None), "SORT": ((0,), None), "SUMIF": ((0, 2), None), # SUMIF(range, criteria, [sum_range]) "AVERAGEIF": ((0, 2), None), # AVERAGEIF(range, criteria, [average_range]) "COUNTIF": ((0,), None), # COUNTIF(range, criteria) "SUMIFS": ((0,), (1, 2)), # SUMIFS(sum_range, criteria_range1, criteria1, ...) "AVERAGEIFS": ((0,), (1, 2)), "MAXIFS": ((0,), (1, 2)), "MINIFS": ((0,), (1, 2)), "COUNTIFS": ((), (0, 2)), # COUNTIFS(criteria_range1, criteria1, ...) "SUMPRODUCT": ALL_ARGS, "VLOOKUP": ((1,), None), "HLOOKUP": ((1,), None), "XLOOKUP": ((1, 2), None), "INDEX": ((0,), None), "MATCH": ((1,), None), "RANK": ((1,), None), "PERCENTILE": ((0,), None), "QUARTILE": ((0,), None), "LARGE": ((0,), None), "SMALL": ((0,), None), "COUNTBLANK": ((0,), None), "ROWS": ((0,), None), "COLUMNS": ((0,), None), "NETWORKDAYS": ((2,), None), # NETWORKDAYS(start_date, end_date, [holidays]) "WORKDAY": ((2,), None), # WORKDAY(start_date, days, [holidays]) } #: ⭐ THE ARGUMENT IS AN ADDRESS, NOT A VALUE. `ROW(B4)` asks what row `B4` is on and must not read #: what is written there; the cell may well be empty. Handled beside `RANGE_ARGS` in `_eval`. ADDR_ARGS = {"ROW": (0,), "COLUMN": (0,)} def _is_range_position(fn, index): """Does `fn` take a shaped range at zero-based argument `index`?""" spec = RANGE_ARGS.get(fn) if spec is None: return False if spec == ALL_ARGS: return True explicit, repeat = spec if index in explicit: return True if repeat and index >= repeat[0] and (index - repeat[0]) % repeat[1] == 0: return True return False def _a1_at(source, i, default_sheet=""): """`(replacement_text, next_index)` if an A1 token starts at `i`, else None. ⭐ `default_sheet` IS WHAT MAKES A WORKBOOK PASS POSSIBLE (W51-T23). An UNQUALIFIED reference means "this tab", and the only moment anything knows which tab that is, is when the formula is read out of a cell that lives on one. So the owning tab is supplied HERE, at rewrite time, and `=G4+1` on `Tab05` becomes `A1REF('G4', 'Tab05')` before `_normal` ever builds a key. A reference that names its own sheet keeps that name; nothing else in the pipeline changes. ⛔ THE ALTERNATIVE WAS MEASURED AND IS WORSE: qualifying the SPEC KEYS alone and leaving the formulas untouched makes cross-tab keys resolvable and breaks every local reference, which the wave-51 prototype recorded as 3,770 blanks against a true 785. """ m = _A1_RE.match(source, i) if not m: return None end = m.end() nxt = end while nxt < len(source) and source[nxt] == " ": nxt += 1 if nxt < len(source) and source[nxt] == "(": return None # a function call, not an address. See the note above. if nxt < len(source) and (source[nxt].isalnum() or source[nxt] in "_$!"): return None # the token does not end here, so it is not an address sheet = m.group(1) or m.group(2) or default_sheet first = (m.group(3) or "") + (m.group(4) or "") if m.group(5): last = m.group(5) + (m.group(6) or "") return f"A1RANGE({first!r}, {last!r}, {sheet!r})", end return f"A1REF({first!r}, {sheet!r})", end def _rewrite(source, sheet=""): """Translate Excel punctuation to Python AST punctuation without touching strings. `sheet` is the tab this formula LIVES ON, and every reference that does not name a tab of its own is read as pointing at that one. See `_a1_at` for why it enters the pipeline here. """ out, i, quote = [], 0, None while i < len(source): c = source[i] if quote: out.append(c) if c == quote: if i + 1 < len(source) and source[i + 1] == quote: out.append(source[i + 1]); i += 2; continue quote = None i += 1; continue # ⭐ AN A1 TOKEN IS ONLY TRIED AT AN IDENTIFIER BOUNDARY. Without this guard the scanner # would happily match the tail of a longer name, so `myB4` would end up holding a reference # to cell B4. The previous SOURCE character decides, not the previous emitted one, because # a `{field}` just before has already been rewritten into something longer. # ⚠ `prev in "_$"` is a TRAP when `prev` is the empty string at position 0: Python answers # True, because "" is a substring of every string. That silently disabled A1 addressing for # any formula STARTING with a reference, which is most of them, while leaving `SUM(B4:B8)` # working because its `B` follows a `(`. Compare against a tuple, which has no such edge. # # ⛔⛔ THIS BLOCK SITS ABOVE THE QUOTE BRANCH, AND THAT ORDER IS THE WHOLE OF D-638 # (W51-T23). It used to sit below, so a leading `'` ALWAYS entered string mode first: # `'Data'!B12` was emitted as the Python string `'Data'` followed by a separately rewritten # `!B12` with an EMPTY sheet name, which cannot parse, and Excel's own quoted spelling came # back as "the formula could not be parsed". The guard below already reads `c in ("$", "'")` # because the author meant this branch to see a quote; it simply never got the chance. # ⭐ MOVING IT IS SAFE BECAUSE `_a1_at` IS ALL OR NOTHING: it answers None unless the whole # `'name'!ADDR` shape matches, so a `'...'` used as TEXT falls straight through to the # quote branch below and keeps working. `"` never reaches here at all, since the guard # admits only letters, `$` and `'`. prev = source[i - 1] if i else "" if (c.isalpha() or c in ("$", "'")) and not (prev.isalnum() or prev in ("_", "$")): # ⭐ A DOTTED EXCEL NAME IS FOLDED BEFORE THE A1 ATTEMPT (W50-T16). `STDEV.P(` must # become `STDEV_P(` before `ast.parse` reads the dot as an attribute access, and it # must happen here, at the identifier boundary, so a dot inside a longer token is # never touched. See `DOTTED_SPELLINGS` for why the pattern names only two functions. dotted = _DOTTED_RE.match(source, i) if dotted: out.append(dotted.group(0).upper().replace(".", "_")) i = dotted.end() continue got = _a1_at(source, i, sheet) if got: text, i = got out.append(text) continue if c in ("'", '"'): quote = c; out.append(c); i += 1; continue if c == "{": end = source.find("}", i + 1) if end < 0: raise FormulaError("a field reference is missing its closing }") key = source[i + 1:end].strip() if not re.fullmatch(r"[A-Za-z0-9_]+", key) or len(key) > MAX_FIELD_KEY: raise FormulaError("a field reference may contain only letters, digits and _") out.append(f"REF({key!r})"); i = end + 1; continue two = source[i:i + 2] if two in ("<=", ">=", "!=", "=="): out.append(two); i += 2; continue if two == "<>": out.append("!="); i += 2; continue if c == "=": out.append("==") elif c == "^": out.append("**") else: out.append(c) i += 1 if quote: raise FormulaError("a text value is missing its closing quote") return "".join(out) def _normal(node, depth=0, compact_ranges=False): if depth > MAX_DEPTH: raise FormulaError("formula is nested too deeply") if isinstance(node, ast.Constant) and isinstance(node.value, (int, float, str, bool)): if isinstance(node.value, float) and not math.isfinite(node.value): raise FormulaError("number is not finite") return {"t": "const", "v": node.value} if isinstance(node, ast.Name) and node.id.upper() in ("TRUE", "FALSE"): return {"t": "const", "v": node.id.upper() == "TRUE"} if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): return {"t": "neg", "e": _normal(node.operand, depth + 1, compact_ranges)} if isinstance(node, ast.BinOp): ops = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Pow: "^", ast.BitAnd: "&"} op = ops.get(type(node.op)) if not op: raise FormulaError("that operator is not supported") return {"t": "bin", "op": op, "l": _normal(node.left, depth + 1, compact_ranges), "r": _normal(node.right, depth + 1, compact_ranges)} if isinstance(node, ast.Compare): if len(node.ops) != 1 or len(node.comparators) != 1: raise FormulaError("comparisons cannot be chained") ops = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Eq: "=", ast.NotEq: "!="} op = ops.get(type(node.ops[0])) if not op: raise FormulaError("that comparison is not supported") return {"t": "cmp", "op": op, "l": _normal(node.left, depth + 1, compact_ranges), "r": _normal(node.comparators[0], depth + 1, compact_ranges)} if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): fn = ALIASES.get(node.func.id.upper(), node.func.id.upper()) # The transport spelling folds back to Excel's own, so `FN_ARITY` and the catalogue are # keyed on `STDEV.P` and a stored AST carries the name a person typed. fn = DOTTED_SPELLINGS.get(fn, fn) if fn == "REF": if len(node.args) != 1 or not isinstance(node.args[0], ast.Constant): raise FormulaError("field reference is malformed") return {"t": "ref", "k": str(node.args[0].value)} if fn in ("A1REF", "A1RANGE"): want = 2 if fn == "A1REF" else 3 if len(node.args) != want or not all(isinstance(x, ast.Constant) for x in node.args): raise FormulaError("cell reference is malformed") vals = [str(x.value) for x in node.args] if fn == "A1REF": return {"t": "a1", "k": a1_key(vals[0], vals[1])} if compact_ranges: bounds = _range_bounds(vals[0], vals[1], vals[2]) return {"t": "a1range", "range": bounds, "rows": bounds[4] - bounds[3] + 1, "cols": bounds[2] - bounds[1] + 1} # The range is expanded HERE, at normalize time, so a malformed or oversized range is a # PARSE error the author sees immediately rather than a surprise at evaluation. # ⭐ `rows` and `cols` RIDE ON THE NODE (W50-T16) because they are known here and are # not recoverable from the key list alone by anything that does not want to re-parse # every address. `_validate_ast` treats them as optional, so a definition serialized # before this change still validates and has its shape derived on the spot. keys = expand_range(vals[0], vals[1], vals[2]) rows, cols = _range_shape(keys) return {"t": "a1range", "keys": keys, "rows": rows, "cols": cols} if fn not in FN_ARITY or node.keywords: raise FormulaError(f"{fn} is not a supported function") lo, hi = FN_ARITY[fn] if not lo <= len(node.args) <= hi: raise FormulaError(f"{fn} takes {lo} to {hi} arguments") return {"t": "call", "fn": fn, "args": [_normal(x, depth + 1, compact_ranges) for x in node.args]} raise FormulaError("formula contains unsupported syntax") _SHEET_TOKEN = re.compile( r'(?P\s+)|(?P"(?:[^"]|"")*")|' r"(?P(?:'[^']*\[[^']*'|\[[^\]]*\][A-Za-z0-9_ ]*)![^ ,()+*/]+)|" r"(?P(?:'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!(?:\$?[A-Za-z]{1,3}\$?[1-9][0-9]*|[A-Za-z_][A-Za-z0-9_.]*))|" r'(?P\$?[A-Za-z]{1,3}\$?[1-9][0-9]*(?![A-Za-z0-9_.]))|' r'(?P(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)|' r'(?P[A-Za-z_\\][A-Za-z0-9_.\\]*)|' r'(?P\#[A-Z0-9/]+[!?]?)|(?P<=|>=|<>|!=|[+*/^&=<>():,%#-])') REFERENCE_ERRORS = {"null_intersection": "#NULL!", "unknown_name": "#NAME?", "external_reference": "#REF!", "invalid_reference": "#REF!", "spill_obstructed": "#SPILL!", "empty_array": "#CALC!"} _ERROR_LITERALS = {"#NULL!": "null_intersection", "#REF!": "invalid_reference", "#NAME?": "unknown_name", "#DIV/0!": "div_zero", "#VALUE!": "bad_value", "#N/A": "no_match", "#NUM!": "bad_number"} _VOLATILE_FUNCTIONS = frozenset(("NOW", "TODAY", "RAND", "OFFSET", "INDIRECT")) _COPY_REFERENCE = re.compile( r'"(?:[^"]|"")*"|(?(?:(?:'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!)?)" r'(?P\$?[A-Za-z]{1,3}\$?[1-9][0-9]*(?![A-Za-z0-9_.]|\s*\()|' r'\$?[A-Za-z]{1,3}:\$?[A-Za-z]{1,3}(?![A-Za-z0-9_.$])|' r'\$?[1-9][0-9]*:\$?[1-9][0-9]*(?![A-Za-z0-9_.$]))') def transform_formula_references(source, drow=0, dcol=0, mode="copy"): """The client transformSheetFormula contract: cells/bands shift; names/text stay literal.""" if mode == "cut" or not (drow or dcol): return source def replace(match): ref = match.group("ref") if not ref: return match.group() shifted = [] for end in ref.split(":"): cell = re.fullmatch(r"(\$?)([A-Za-z]+)(\$?)([0-9]+)", end) if cell: c = col_to_index(cell[2]) + (0 if cell[1] else dcol) r = int(cell[4]) + (0 if cell[3] else drow) if not (1 <= c <= 16384 and 1 <= r <= 1048576): return "#REF!" shifted.append(cell[1] + index_to_col(c) + cell[3] + str(r)) else: fixed = end.startswith("$"); raw = end.lstrip("$"); column = raw.isalpha() value = (col_to_index(raw) if column else int(raw)) + (0 if fixed else dcol if column else drow) if not 1 <= value <= (16384 if column else 1048576): return "#REF!" shifted.append(("$" if fixed else "") + (index_to_col(value) if column else str(value))) return match.group("prefix") + ":".join(shifted) return _COPY_REFERENCE.sub(replace, source) def _normalize_named_ranges(value): if isinstance(value, dict): value = [{"name": name, **(entry if isinstance(entry, dict) else {"ref": entry})} for name, entry in value.items()] return tuple(dict(entry) for entry in (value or ()) if isinstance(entry, dict) and isinstance(entry.get("name"), str) and isinstance(entry.get("ref"), str)) def _sheet_syntax(source, sheet, named_ranges=(), active_names=(), address="", budget=None): """Reference operators share one AST with arithmetic; names bind without string eval. The original token rides on each address/name node. Names are local then global and remain names when a formula is copied. Dynamic text is parsed as a reference, never code. """ if len(source) > MAX_SOURCE: raise FormulaError("formula source is too long") if budget is None: named_ranges = _normalize_named_ranges(named_ranges) budget = [MAX_NODES] if budget is None else budget tokens, pos = [], 0 text = _expand_bands(re.sub(r'"(?:[^"]|"")*"|(?:_xlfn\.|_xlws\.|_xludf\.)+(?=[A-Za-z_][A-Za-z0-9_.]*\s*\()', lambda match: match[0] if match[0].startswith('"') else '', source, flags=re.I)) while pos < len(text): match = _SHEET_TOKEN.match(text, pos) if not match: raise FormulaError("the formula could not be parsed") tokens.append((match.lastgroup, match.group())) if len(tokens) > MAX_NODES * 2: raise FormulaError("formula has too many tokens") pos = match.end() # Whitespace is intersection only between operands, not around punctuation/functions. clean = [] for index, token in enumerate(tokens): if token[0] != "space": clean.append(token) continue prev = clean[-1] if clean else None nxt = next((t for t in tokens[index + 1:] if t[0] != "space"), None) if (prev and nxt and (prev[0] in ("cell", "qualified", "name") or prev[1] == ")") and (nxt[0] in ("cell", "qualified", "name") or nxt[1] == "(") and not (prev[0] == "name" and nxt[1] == "(")): clean.append(("op", " ")) index = 0 def peek(): return clean[index][1] if index < len(clean) else "" def take(): nonlocal index if index >= len(clean): raise FormulaError("the formula is incomplete") token = clean[index]; index += 1 return token def reference(token, qualifier=""): own = qualifier or sheet if re.fullmatch(_A1_CELL, token): key = a1_key(token, own) _, c, r = _address_parts(key) if c > 16384 or r > 1048576: return {"t": "error", "code": "invalid_reference"} return {"t": "a1", "k": key, "token": token} name = token.upper() candidates = [n for n in named_ranges if str(n.get("name", "")).upper() == name] local = next((n for n in candidates if str(n.get("sheet", "")).upper() == own.upper()), None) target = local or next((n for n in candidates if not n.get("sheet")), None) identity = (own.upper(), name) if target is None: bound = {"t": "error", "code": "unknown_name"} elif identity in active_names: bound = {"t": "error", "code": "circular_reference"} elif len(active_names) >= MAX_DEPTH: raise FormulaError("names are nested too deeply") else: # A relative defined name is a template anchored at base (A1 for legacy names). # Its dependency is bound at the actual caller address, including mixed-$ axes. _, bc, br = _address_parts(str(target.get("base") or "A1").replace("$", "").upper()) _, cc, cr = _address_parts(address or "A1") shifted = transform_formula_references(str(target.get("ref", "")).lstrip("="), cr-br, cc-bc) bound = _sheet_syntax(shifted, str(target.get("sheet") or sheet), named_ranges, (*active_names, identity), address, budget) return {"t": "name", "name": name, "sheet": own, "token": token, "e": bound} def atom(depth): budget[0] -= 1 if budget[0] < 0: raise FormulaError("formula has too many expanded nodes") kind, token = take() if kind == "num": return {"t": "const", "v": float(token)} if kind == "str": return {"t": "const", "v": token[1:-1].replace('""', '"')} if kind == "external": return {"t": "error", "code": "external_reference"} if kind == "err": return {"t": "error", "code": _ERROR_LITERALS.get(token, "bad_value")} if kind in ("cell", "name"): if peek() == "(": take(); fn = ALIASES.get(token.upper(), token.upper()); args = [] if peek() != ")": while True: args.append({"t": "const", "v": None} if peek() in (",", ")") else expr(1, depth + 1)) if peek() != ",": break take() if take()[1] != ")": raise FormulaError("function arguments are incomplete") if fn not in FN_ARITY: return {"t": "error", "code": "unknown_name"} lo, hi = FN_ARITY[fn] if not lo <= len(args) <= hi: raise FormulaError("function arity is invalid") return {"t": "call", "fn": fn, "args": args} if token.upper() in ("TRUE", "FALSE"): return {"t": "const", "v": token.upper() == "TRUE"} return reference(token) if kind == "qualified": qualifier, token = token.rsplit("!", 1) bound = reference(token, qualifier.strip("'").replace("''", "'")) bound["token"] = qualifier + "!" + token return bound if token == "(": node = expr(0, depth + 1) if take()[1] != ")": raise FormulaError("parenthesis is incomplete") return node if token in ("+", "-"): node = expr(6, depth + 1) return node if token == "+" else {"t": "neg", "e": node} raise FormulaError("the formula could not be parsed") precedence = {",": 0, "=": 1, "<>": 1, "!=": 1, "<": 1, ">": 1, "<=": 1, ">=": 1, "&": 2, "+": 3, "-": 3, "*": 4, "/": 4, "^": 5, " ": 7, ":": 8} def expr(minimum, depth): if depth > MAX_DEPTH: raise FormulaError("formula is nested too deeply") node = atom(depth) if peek() == "#": take(); node = {"t": "spill", "e": node} while peek() in precedence and precedence[peek()] >= minimum: budget[0] -= 1 if budget[0] < 0: raise FormulaError("formula has too many expanded nodes") op = take()[1]; right = expr(precedence[op] + 1, depth + 1) if op == ":" and node["t"] == right["t"] == "a1": a, b = node["k"].rpartition("!"), right["k"].rpartition("!") # An unqualified end inherits the explicit start's tab. end_sheet = b[0] if "!" in right.get("token", "") else a[0] bounds = _range_bounds(a[2], b[2], a[0]) node = {"t": "a1range", "range": bounds, "rows": bounds[4]-bounds[3]+1, "cols": bounds[2]-bounds[1]+1} if end_sheet == a[0] else {"t": "error", "code": "invalid_reference"} elif op in (":", " ", ","): node = {"t": "reference_op", "op": op, "l": node, "r": right} else: node = {"t": "cmp" if precedence[op] == 1 else "bin", "op": "!=" if op == "<>" else op, "l": node, "r": right} return node root = expr(0, 0) if index != len(clean): raise FormulaError("the formula has trailing tokens") return root def parse_formula(source, *, sheet="", compact_ranges=False, named_ranges=(), address=""): """One formula's stored definition. `sheet` is the tab it lives on, or "" for a grid field. ⭐ KEYWORD ONLY, AND DEFAULTED TO "", so every caller that has no notion of a tab keeps the definition it always had: with no sheet, an unqualified reference still keys as the bare `B4` that `evaluate_fields` and `routes_query.py::parse_formula` already read. Only a Sheet supplies a tab, and only then do this formula's own references key as `TAB!B4`. """ source = str(source or "") sheet = str(sheet or "") if not source.strip(): raise FormulaError("the formula is empty") if len(source) > MAX_SOURCE: raise FormulaError(f"formula longer than {MAX_SOURCE} characters") if compact_ranges: root = _sheet_syntax(source, sheet, named_ranges, address=address) else: root = None try: # Regex patterns such as ``"\\s"`` are data for REGEX_* rather than Python escapes. # Python 3.12 warns while parsing them even though the string is valid for this grammar. with warnings.catch_warnings(): warnings.simplefilter("ignore", SyntaxWarning) parsed = ast.parse(_rewrite(source, sheet), mode="eval") if root is None else None except (SyntaxError, ValueError) as exc: raise FormulaError("the formula could not be parsed") from exc if parsed is not None and sum(1 for _ in ast.walk(parsed)) > MAX_NODES: raise FormulaError(f"formula has more than {MAX_NODES} nodes") root = root if root is not None else _normal(parsed.body, compact_ranges=compact_ranges) refs = [] # ⭐ `cells` IS A SECOND, SEPARATE LIST AND NOT A MERGE INTO `refs`. `refs` names FIELD keys and # is already persisted in every stored definition, read by `evaluate_fields`, `evaluate_batch` # and the contract DTO; folding cell addresses into it would hand every one of those consumers # a key that is not a field. `cells` is additive, so an existing definition simply carries an # empty one. cells, ranges, precedents = [], [], [] def walk(row): if row["t"] == "ref" and row["k"] not in refs: refs.append(row["k"]) if row["t"] == "a1" and row["k"] not in cells: cells.append(row["k"]) precedents.append({"cell": row["k"]}) if row["t"] == "a1range": if "range" in row: ranges.append(row["range"]) precedents.append({"range": row["range"]}) for key in row.get("keys") or (): if key not in cells: cells.append(key) for key in ("e", "l", "r"): if isinstance(row.get(key), dict): walk(row[key]) for child in row.get("args") or (): walk(child) walk(root) result = {"version": AST_VERSION, "source": source, "ast": root, "refs": refs, "cells": cells} if compact_ranges: def volatile(node): return (node.get("fn") in _VOLATILE_FUNCTIONS or any(volatile(node[k]) for k in ("e", "l", "r") if isinstance(node.get(k), dict)) or any(volatile(child) for child in node.get("args", ()))) result.update(ranges=ranges, precedents=precedents, volatile=volatile(root), sheet=sheet) return result def _num(v): if isinstance(v, bool) or v is None or v == "": return None try: n = float(v) except (TypeError, ValueError): return None return n if math.isfinite(n) else None def _text(v): if v is None: return "" if isinstance(v, bool): return "TRUE" if v else "FALSE" if isinstance(v, float) and v.is_integer(): return str(int(v)) return str(v) def _date(v): try: return dt.date.fromisoformat(str(v)[:10]) except (TypeError, ValueError): return None def _round(v, places=0, mode=ROUND_HALF_UP): n, p = _num(v), _num(places) if n is None or p is None: return None q = Decimal("1").scaleb(-int(p)) return float(Decimal(str(n)).quantize(q, rounding=mode)) def _safe_regex(pattern, subject): pattern, subject = str(pattern), str(subject) if len(pattern) > 120 or len(subject) > 10000 or "{" in pattern: raise FormulaError("regular expression exceeds the safe bounds") if re.search(r"\([^)]*[+*][^)]*\)[+*]", pattern): raise FormulaError("nested unbounded regular expression is refused") return pattern, subject #: The canonical form `a1_key` emits: an upper-case address with no `$`, optionally behind a sheet #: name and a `!`. Used by `_validate_ast`, which sees serialized keys rather than parsed tokens. _A1_KEY_ADDR = re.compile(r"[A-Z]{1,3}[1-9][0-9]{0,6}") def _is_a1_key(key): if not isinstance(key, str) or not key or len(key) > 96: return False sheet, sep, addr = key.rpartition("!") if sep and (not sheet or len(sheet) > 64): return False return bool(_A1_KEY_ADDR.fullmatch(addr)) def _require_node_keys(node, expected): if set(node) != set(expected): raise FormulaError("formula AST node fields do not match the versioned schema") def _validate_ast(node, depth=0, refs=None, count=None): """Validate a serialized AST independently of the parser before strict API evaluation.""" refs = [] if refs is None else refs count = [0] if count is None else count count[0] += 1 if depth > MAX_DEPTH or count[0] > MAX_NODES or not isinstance(node, dict): raise FormulaError("formula AST exceeds the safe bounds") kind = node.get("t") if kind == "const": _require_node_keys(node, ("t", "v")) value = node.get("v") if not isinstance(value, (int, float, str, bool)) or ( isinstance(value, float) and not math.isfinite(value)): raise FormulaError("formula AST constant is invalid") elif kind == "ref": _require_node_keys(node, ("t", "k")) key = node.get("k") if (not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_]+", key) or len(key) > MAX_FIELD_KEY): raise FormulaError("formula AST field reference is invalid") if key not in refs: refs.append(key) elif kind == "a1": # ⛔⛔ WITHOUT THIS BRANCH THE STRICT PATH REFUSED EVERY A1 FORMULA (latent since W49-T03, # closed by W50-T16). `_validate_ast` fell through to "formula AST node is not supported", # so `validate_definition(..., require_source=True)` could not accept `SUM(B4:B8)` at all. # It did not bite `evaluate_sheet`, which evaluates NON-strict, which is exactly why it # went unnoticed for a whole wave. # ⚠ AN A1 KEY IS NOT A REF. `parse_formula` puts cell addresses in a definition's `cells` # and field keys in `refs`, so nothing is appended to `refs` here and # `validate_definition`'s refs comparison is unaffected. _require_node_keys(node, ("t", "k")) if not _is_a1_key(node.get("k")): raise FormulaError("formula AST cell reference is invalid") elif kind == "a1range": keys = node.get("keys") if set(node) == {"t", "keys"}: rows = cols = None else: _require_node_keys(node, ("t", "keys", "rows", "cols")) rows, cols = node.get("rows"), node.get("cols") if not isinstance(keys, list) or not keys or len(keys) > MAX_RANGE_CELLS: raise FormulaError("formula AST cell range is invalid") if not all(_is_a1_key(key) for key in keys): raise FormulaError("formula AST cell range is invalid") if rows is not None or cols is not None: if (isinstance(rows, bool) or isinstance(cols, bool) or not isinstance(rows, int) or not isinstance(cols, int) or rows < 1 or cols < 1 or rows * cols != len(keys)): raise FormulaError("formula AST cell range shape is invalid") elif kind == "neg": _require_node_keys(node, ("t", "e")) _validate_ast(node.get("e"), depth + 1, refs, count) elif kind in ("bin", "cmp"): _require_node_keys(node, ("t", "op", "l", "r")) allowed = {"+", "-", "*", "/", "^", "&"} if kind == "bin" else { "<", "<=", ">", ">=", "=", "!="} if node.get("op") not in allowed: raise FormulaError("formula AST operator is invalid") _validate_ast(node.get("l"), depth + 1, refs, count) _validate_ast(node.get("r"), depth + 1, refs, count) elif kind == "call": _require_node_keys(node, ("t", "fn", "args")) fn, args = node.get("fn"), node.get("args") if fn not in FN_ARITY or not isinstance(args, list): raise FormulaError("formula AST function is invalid") lo, hi = FN_ARITY[fn] if not lo <= len(args) <= hi: raise FormulaError("formula AST function arity is invalid") for child in args: _validate_ast(child, depth + 1, refs, count) else: raise FormulaError("formula AST node is not supported") return refs def validate_definition(definition, *, require_source=False): """Refuse any serialized definition that is not exactly reproducible by this parser. Checking the AST alone would let a caller display one ``source`` while asking the server to execute a different tree. API consumers therefore send the parser-issued envelope and strict evaluation reparses its source before accepting it. """ if not isinstance(definition, dict) or isinstance(definition.get("version"), bool) or ( definition.get("version") != AST_VERSION): raise FormulaError("formula AST version is not supported") refs = _validate_ast(definition.get("ast")) metadata_refs = definition.get("refs") if not isinstance(metadata_refs, list) or metadata_refs != refs: raise FormulaError("formula AST references do not match its metadata") source = definition.get("source") if require_source and not isinstance(source, str): raise FormulaError("formula source is required for authoritative evaluation") if isinstance(source, str): reparsed = parse_formula(source) if reparsed["ast"] != definition.get("ast") or reparsed["refs"] != metadata_refs: raise FormulaError("formula source does not match its AST") return refs def evaluate_result(definition, row, *, today=None, strict=False): """Evaluate one definition and return the shared value/error DTO.""" diagnostics = [] try: if strict: validate_definition(definition, require_source=True) elif not isinstance(definition, dict) or definition.get("version") != AST_VERSION: return {"value": None, "error": "invalid_definition"} value = _eval(definition.get("ast"), row if isinstance(row, dict) else {}, today or dt.date.today().isoformat(), diagnostics) if diagnostics: value = None if isinstance(value, bool) and not isinstance(row, _SheetInputs): value = "TRUE" if value else "FALSE" elif isinstance(value, float) and not math.isfinite(value): value = None elif isinstance(value, Range) and isinstance(row, _SheetInputs): pass elif value is not None and not isinstance(value, (int, float, str)): value = None diagnostics.append("evaluation_error") return {"value": value, "error": None if value is not None else (diagnostics[0] if diagnostics else "blank")} except FormulaError: if strict: raise return {"value": None, "error": "invalid_definition"} except (ArithmeticError, TypeError, ValueError, OverflowError, KeyError, re.error): return {"value": None, "error": "evaluation_error"} def evaluate(definition, row, *, today=None, strict=False): """Backward-compatible value projection of :func:`evaluate_result`.""" return evaluate_result(definition, row, today=today, strict=strict)["value"] def _diagnose(diagnostics, code): if diagnostics is not None and code not in diagnostics: diagnostics.append(code) def _reference_node(node): if node.get("t") == "name": return _reference_node(node["e"]) return (node.get("t") in ("a1", "a1range", "reference_op", "spill") or (node.get("t") == "call" and node.get("fn") in ("OFFSET", "INDIRECT"))) def _reference_areas(node, row, today, diagnostics): """Resolve rectangles, not values. Unions retain each area and overlapping occurrences.""" kind = node.get("t") if kind == "error": _diagnose(diagnostics, node["code"]); return [] if kind == "name": return _reference_areas(node["e"], row, today, diagnostics) if kind == "spill": child = node["e"] if child.get("t") != "a1" or not isinstance(row, _SheetInputs): _diagnose(diagnostics, "invalid_reference"); return [] key = child["k"] row.get(key) owned = row.engine.spills.get(key) if not owned: _diagnose(diagnostics, "invalid_reference"); return [] return [owned["range"]] if kind == "a1": sheet, col, r = _address_parts(node["k"]) return [(sheet, col, col, r, r)] if kind == "a1range": if "range" in node: return [node["range"]] keys = node["keys"] return [_range_bounds(keys[0].rsplit("!", 1)[-1], keys[-1].rsplit("!", 1)[-1], _sheet_half(keys[0]))] if kind == "reference_op": left = _reference_areas(node["l"], row, today, diagnostics) right = _reference_areas(node["r"], row, today, diagnostics) if diagnostics: return [] if node["op"] == ",": return left + right if node["op"] == ":": if len(left) != 1 or len(right) != 1 or left[0][0] != right[0][0]: _diagnose(diagnostics, "invalid_reference"); return [] a, b = left[0], right[0] return [(a[0], min(a[1], b[1]), max(a[2], b[2]), min(a[3], b[3]), max(a[4], b[4]))] result = [] for a in left: for b in right: area = (a[0], max(a[1], b[1]), min(a[2], b[2]), max(a[3], b[3]), min(a[4], b[4])) if a[0] == b[0] and area[1] <= area[2] and area[3] <= area[4]: result.append(area) if not result: _diagnose(diagnostics, "null_intersection") return result if kind == "call" and node["fn"] == "OFFSET": base = _reference_areas(node["args"][0], row, today, diagnostics) args = [_num(_eval(arg, row, today, diagnostics)) for arg in node["args"][1:]] if len(base) != 1 or any(v is None for v in args): _diagnose(diagnostics, "bad_value"); return [] s, c0, c1, r0, r1 = base[0] dr, dc = (int(args[0]), int(args[1])) height = int(args[2]) if len(args) > 2 else r1-r0+1 width = int(args[3]) if len(args) > 3 else c1-c0+1 area = (s, c0+dc, c0+dc+width-1, r0+dr, r0+dr+height-1) if height < 1 or width < 1: _diagnose(diagnostics, "invalid_reference"); return [] return _checked_areas([area], row, diagnostics) if kind == "call" and node["fn"] == "INDIRECT": text = _eval(node["args"][0], row, today, diagnostics) if not isinstance(text, str): _diagnose(diagnostics, "invalid_reference"); return [] if "[" in text or "]" in text: # R1C1 bracket offsets are allowed only under the explicit second FALSE argument. r1c1 = len(node["args"]) == 2 and _eval(node["args"][1], row, today, diagnostics) is False if not r1c1 or not re.fullmatch(r"R(?:\[-?\d+\]|\d*)C(?:\[-?\d+\]|\d*)", text, re.I): _diagnose(diagnostics, "external_reference"); return [] here = row.get(SHEET_ADDR_KEY, "") sheet = _sheet_half(here) if len(node["args"]) == 2 and _eval(node["args"][1], row, today, diagnostics) is False: m = re.fullmatch(r"R(\[-?\d+\]|\d*)C(\[-?\d+\]|\d*)", text, re.I) if not m or not here: _diagnose(diagnostics, "invalid_reference"); return [] _, col, r = _address_parts(here) def coord(raw, origin): return origin + int(raw[1:-1]) if raw.startswith("[") else int(raw) if raw else origin r, col = coord(m[1], r), coord(m[2], col) if min(r, col) < 1: _diagnose(diagnostics, "invalid_reference"); return [] text = index_to_col(col) + str(r) try: target = row.engine.reference_syntax(text, sheet, here) if isinstance(row, _SheetInputs) else _sheet_syntax(text, sheet, address=here) except FormulaError: _diagnose(diagnostics, "invalid_reference"); return [] if (not _reference_node(target) and target.get("t") != "error") or target.get("t") == "call": _diagnose(diagnostics, "invalid_reference"); return [] return _checked_areas(_reference_areas(target, row, today, diagnostics), row, diagnostics) _diagnose(diagnostics, "invalid_reference") return [] def _checked_areas(areas, row, diagnostics): for s, c0, c1, r0, r1 in areas: if min(c0, r0) < 1 or c1 > 16384 or r1 > 1048576: _diagnose(diagnostics, "invalid_reference"); return [] if isinstance(row, _SheetInputs) and row.engine.sheets is not None and s and s not in row.engine.sheets: _diagnose(diagnostics, "unknown_sheet"); return [] return areas def _area_values(areas, row, sparse=True): for bounds in areas: if sparse and isinstance(row, _SheetInputs): yield from row.range_values(bounds) else: s, c0, c1, r0, r1 = bounds if (c1-c0+1)*(r1-r0+1) > MAX_RANGE_CELLS: raise FormulaError("range is too large") for r in range(r0, r1+1): for c in range(c0, c1+1): yield row.get(a1_key(index_to_col(c)+str(r), s)) def _excel_number(value): return float(format(value, ".15g")) if isinstance(value, (int, float)) and not isinstance(value, bool) else value def _logical(value, diagnostics): if isinstance(value, (bool, int, float)) or value is None: return bool(value) if isinstance(value, str) and value.upper() in ("TRUE", "FALSE"): return value.upper() == "TRUE" _diagnose(diagnostics, "bad_value") return False def _format_rule(node, formats): formats = [item for item in formats if item] kind, fn = node.get("t"), node.get("fn") if kind == "cmp" or (kind == "bin" and node["op"] in ("&", "^")): return None if kind == "call": if fn in ("DATE", "DATEVALUE", "TODAY", "NOW", "EDATE", "EOMONTH", "WORKDAY", "DATEADD"): return {"kind": "date"} if fn in ("IRR", "XIRR"): return {"kind": "percent", "decimals": 2} if fn not in ("IF", "IFS", "IFERROR", "IFNA", "SWITCH", "CHOOSE", "SUM", "AVERAGE", "MIN", "MAX", "SUMIF", "SUMIFS", "AVERAGEIF", "AVERAGEIFS", "INDEX", "XLOOKUP", "VLOOKUP", "HLOOKUP", "OFFSET", "INDIRECT", "FILTER", "SORT", "ROUND", "ROUNDUP", "ROUNDDOWN", "ABS", "ADD", "MULTIPLY", "FV"): return None if kind == "bin" and len(formats) > 1: kinds = [f.get("kind") if isinstance(f, dict) else f for f in formats] if node["op"] == "-" and kinds[:2] == ["date", "date"]: return None if node["op"] == "/" and kinds[0] == kinds[1]: return {"kind": "percent", "decimals": 2} return next((f for f in formats if isinstance(f, dict) and f.get("kind") in ("currency", "date")), formats[0] if formats else None) def _eval(node, row, today, diagnostics=None): if not isinstance(row, _SheetInputs): return _eval_value(node, row, today, diagnostics) row.format_stack.append([]) try: value = _eval_value(node, row, today, diagnostics) fmt = _format_rule(node, row.format_stack[-1]) row.last_format = fmt if ((isinstance(value, (int, float, Range)) and not isinstance(value, bool)) or (isinstance(value, str) and isinstance(fmt, dict) and fmt.get("kind") == "date")) else None value = _excel_number(value) finally: row.format_stack.pop() if row.format_stack: row.format_stack[-1].append(row.last_format) return value def _eval_value(node, row, today, diagnostics=None): kind = node.get("t") if isinstance(node, dict) else None if kind == "const": return node.get("v") if kind == "error": _diagnose(diagnostics, node["code"]); return None if kind == "name" and not _reference_node(node["e"]): return _eval(node["e"], row, today, diagnostics) if kind in ("name", "reference_op", "spill") or (kind == "call" and node["fn"] in ("OFFSET", "INDIRECT")): areas = _reference_areas(node, row, today, diagnostics) if len(areas) == 1 and areas[0][1] == areas[0][2] and areas[0][3] == areas[0][4]: area = areas[0] return row.get(a1_key(index_to_col(area[1])+str(area[3]), area[0])) if isinstance(row, _SheetInputs) and len(areas) == 1: area = areas[0] return Range(_area_values(areas, row, sparse=False), area[4]-area[3]+1, area[2]-area[1]+1) if not diagnostics: _diagnose(diagnostics, "range_outside_function") return None if kind == "ref": key = node.get("k") if key not in row: _diagnose(diagnostics, "unknown_ref") return row.get(key) if kind == "a1": # ⭐ A1 VALUES ARRIVE THROUGH `row`, KEYED BY ADDRESS, and that is deliberately not a new # callback parameter. `row` is already threaded through every evaluator path, so a Sheet # supplies `{"B4": 42, "SHEET2!C3": 7}` and nothing else in this file changes shape. key = node.get("k") if key not in row: _diagnose(diagnostics, "unknown_ref") return row.get(key) if kind == "a1range": if isinstance(row, _SheetInputs): return _range_arg(node, row, today, diagnostics) # ⛔ A BARE RANGE IS NOT A VALUE. `=B4:B8` alone has no meaning; a range is only ever an # ARGUMENT to an aggregate, and the call dispatch below is what splices it in. Returning # the list here would let `=B4:B8*2` silently produce nonsense. _diagnose(diagnostics, "range_outside_function") return None if kind == "neg": value = _eval(node["e"], row, today, diagnostics) if isinstance(value, Range): return _array_binary(value, -1, "*", diagnostics) n = _num(value) return None if n is None else -n if kind == "bin": left = _eval(node["l"], row, today, diagnostics) right = _eval(node["r"], row, today, diagnostics) if isinstance(left, Range) or isinstance(right, Range): return _array_binary(left, right, node["op"], diagnostics) if node["op"] == "&": return _text(left) + _text(right) if isinstance(row, _SheetInputs): left, right = 0 if left is None else left, 0 if right is None else right left, right = int(left) if isinstance(left, bool) else left, int(right) if isinstance(right, bool) else right # ISO is the one date value shape shared by import, rendering and database filters. Give # that same value Excel's day arithmetic here instead of forcing a caller to replace it # with a serial number that the date filter cannot read. Date-date subtraction answers a # day count; date +/- number answers another ISO date. Other operators remain numeric. if node["op"] in ("+", "-"): left_day, right_day = _date(left), _date(right) left_num, right_num = _num(left), _num(right) try: if left_day is not None and right_day is not None and node["op"] == "-": return (left_day - right_day).days if left_day is not None and right_num is not None: shift = right_num if node["op"] == "+" else -right_num if int(shift) == shift: return (left_day + dt.timedelta(days=int(shift))).isoformat() if right_day is not None and left_num is not None and node["op"] == "+": if int(left_num) == left_num: return (right_day + dt.timedelta(days=int(left_num))).isoformat() except (OverflowError, ValueError): _diagnose(diagnostics, "bad_value") return None a, b = _num(left), _num(right) if a is None or b is None: return None if node["op"] == "/" and b == 0: _diagnose(diagnostics, "div_zero") return None return {"+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b, "/": lambda: a / b, "^": lambda: a ** b}[node["op"]]() if kind == "cmp": a = _eval(node["l"], row, today, diagnostics) b = _eval(node["r"], row, today, diagnostics) if isinstance(a, Range) or isinstance(b, Range): return _array_binary(a, b, node["op"], diagnostics) if isinstance(row, _SheetInputs): def comparison(value): if isinstance(value, bool): return (2, value) if isinstance(value, str): return (1, value.casefold()) return (0, _excel_number(value or 0)) x, y = comparison(a), comparison(b) else: if a is None or b is None: return None na, nb = _num(a), _num(b) if (na is None) != (nb is None): return None x, y = (na, nb) if na is not None else (str(a).casefold(), str(b).casefold()) return {"<": x < y, "<=": x <= y, ">": x > y, ">=": x >= y, "=": x == y, "!=": x != y}[node["op"]] if kind == "call": fn = node["fn"] if fn in ("RAND", "NOW", "TODAY") and isinstance(row, _SheetInputs): return row.engine.volatile_value(node, fn) if fn == "RAND": return random.random() # IF/IFERROR are lazy, so an unselected bad branch cannot blank the result. if fn == "IF": cond = _eval(node["args"][0], row, today, diagnostics) if isinstance(row, _SheetInputs): cond = _logical(cond, diagnostics) elif not isinstance(cond, bool): return None pick = 1 if cond else 2 return (_eval(node["args"][pick], row, today, diagnostics) if pick < len(node["args"]) else None) if fn == "IFERROR": # A handled failure is not an error of the whole formula, so diagnostics from the # losing branch remain local. local = [] try: first = _eval(node["args"][0], row, today, local) except (ArithmeticError, TypeError, ValueError, OverflowError, KeyError, re.error, FormulaError, _ReferenceFault): first = None; local.append("evaluation_error") if isinstance(row, _SheetInputs): answer = _eval(node["args"][1], row, today, diagnostics) if local else first return "" if answer is None and not diagnostics else answer return first if first is not None and not local else _eval(node["args"][1], row, today, diagnostics) if fn == "IFS": # Conditions are read in order and STOP at the first TRUE one, so a later branch that # would refuse never runs. Excel answers a no-match error when none of them is TRUE. pairs = node.get("args") or () for index in range(0, len(pairs) - 1, 2): condition = _eval(pairs[index], row, today, diagnostics) if isinstance(row, _SheetInputs): condition = _logical(condition, diagnostics) elif not isinstance(condition, bool): return None if condition: return _eval(pairs[index + 1], row, today, diagnostics) _diagnose(diagnostics, "no_match") return None if fn == "IFNA": # ⭐ IFNA CATCHES ONE CLASS AND PASSES THE REST THROUGH, which is what separates it from # IFERROR. A lookup that found nothing is answered; a division by zero is still a # division by zero and its diagnostic is handed back to the caller unchanged. local = [] try: first = _eval(node["args"][0], row, today, local) except _ReferenceFault as exc: if row.engine.errors[str(exc)] != "no_match": raise first = None; local.append("no_match") if "no_match" in local: first = _eval(node["args"][1], row, today, diagnostics) return "" if first is None and isinstance(row, _SheetInputs) and not diagnostics else first for code in local: _diagnose(diagnostics, code) return "" if first is None and isinstance(row, _SheetInputs) and not local else first if fn == "ISERROR": # The whole job is to ask whether a refusal happened, so the refusal must stay LOCAL. local = [] try: _eval(node["args"][0], row, today, local) except (ArithmeticError, TypeError, ValueError, OverflowError, KeyError, re.error, FormulaError, _ReferenceFault): return True return bool(local) # ⭐ A POSITIONAL FUNCTION TAKES ITS RANGES BY POSITION (W50-T16). See `RANGE_ARGS` for why # the splice below is never applied to one of these: it would shift every later argument. if fn in RANGE_ARGS or fn in ADDR_ARGS: addresses = ADDR_ARGS.get(fn, ()) raw = list(node.get("args") or ()) args = [] for index, child in enumerate(raw): if index in addresses: args.append(_addr_arg(child, diagnostics)) elif _is_range_position(fn, index): args.append(_range_arg(child, row, today, diagnostics)) else: args.append(_eval(child, row, today, diagnostics)) if not raw and fn in ADDR_ARGS: # ROW() and COLUMN() with no argument mean THIS cell. In a grid formula field there # is no such thing, so there is no answer to give and the formula refuses. here = row.get(SHEET_ADDR_KEY) if not here: _diagnose(diagnostics, "bad_value") return None args.append(here) return _call(fn, args, today, diagnostics) # ⭐ RANGES FLATTEN HERE, INTO THE SAME FLAT LIST `_call` ALREADY TAKES. `SUM`, `AVERAGE`, # `COUNT`, `MIN` and `MAX` are declared `(1, MANY)` and simply iterate their argument list, # so a range must become MORE ARGUMENTS rather than one list-shaped argument. Doing it here # instead of inside `_call` is what keeps all 46 functions unchanged. args = [] if fn in ("COUNT", "COUNTA") and isinstance(row, _SheetInputs): row.ignore_reference_errors += 1 try: for child in node.get("args") or (): if _reference_node(child): args.extend(_area_values(_reference_areas(child, row, today, diagnostics), row)) else: args.append(_eval(child, row, today, diagnostics)) finally: row.ignore_reference_errors -= 1 return _call(fn, args, today, diagnostics) for x in node.get("args") or (): if _reference_node(x) and x.get("t") not in ("a1", "a1range"): args.extend(_area_values(_reference_areas(x, row, today, diagnostics), row)) continue if isinstance(x, dict) and x.get("t") == "a1range": if "range" in x and isinstance(row, _SheetInputs): args.extend(row.range_values(x["range"])) continue for key in x.get("keys") or (): if key not in row: _diagnose(diagnostics, "unknown_ref") args.append(row.get(key)) else: value = _eval(x, row, today, diagnostics) if isinstance(value, Range) and fn in ("SUM", "AVERAGE", "COUNT", "COUNTA", "MIN", "MAX", "SUMPRODUCT"): args.extend(value.values) else: args.append(value) return _call(fn, args, today, diagnostics) raise FormulaError("formula AST node is not supported") def _addr_arg(node, diagnostics): """The ADDRESS a1 node names, as a key. Anything else is not an address and refuses.""" if isinstance(node, dict) and node.get("t") == "a1": return node.get("k") _diagnose(diagnostics, "bad_value") return None def _range_arg(node, row, today, diagnostics): """One argument as a shaped `Range`. A scalar standing there becomes a 1 by 1 rectangle.""" if _reference_node(node) and node.get("t") not in ("a1", "a1range"): areas = _reference_areas(node, row, today, diagnostics) if len(areas) != 1: _diagnose(diagnostics, "bad_value"); return Range.scalar(None) s, c0, c1, r0, r1 = areas[0] return Range(_area_values(areas, row, sparse=False), r1-r0+1, c1-c0+1) if isinstance(node, dict) and node.get("t") == "a1range": if "range" in node and isinstance(row, _SheetInputs): bounds = node["range"] size = node["rows"] * node["cols"] if size > MAX_RANGE_CELLS: # Shaped array/lookup execution is extended by the array engine. Aggregates # already read sparse ranges without enumerating blanks. _diagnose(diagnostics, "range_too_large") return Range.scalar(None) return Range([row.get(a1_key(index_to_col(c) + str(r), bounds[0])) for r in range(bounds[3], bounds[4] + 1) for c in range(bounds[1], bounds[2] + 1)], node["rows"], node["cols"]) keys = list(node.get("keys") or ()) rows, cols = node.get("rows"), node.get("cols") if (isinstance(rows, bool) or isinstance(cols, bool) or not isinstance(rows, int) or not isinstance(cols, int) or rows * cols != len(keys)): rows, cols = _range_shape(keys) # ⭐ A KEY MISSING FROM `row` IS A BLANK CELL HERE, NOT AN UNKNOWN REFERENCE, and that is # the one place this path deliberately differs from the splice above. A rectangle almost # always contains empty cells; that is what COUNTBLANK counts and what SUM skips. Calling # it `unknown_ref` would refuse the commonest formula on any real sheet. return Range([row.get(key) for key in keys], rows, cols) value = _eval(node, row, today, diagnostics) return value if isinstance(value, Range) else Range.scalar(value) def _array_binary(left, right, op, diagnostics): a, b = _as_range(left), _as_range(right) rows, cols = max(a.rows, b.rows), max(a.cols, b.cols) if any(x.rows not in (1, rows) or x.cols not in (1, cols) for x in (a, b)): _diagnose(diagnostics, "bad_value"); return None values = [] for r in range(rows): for c in range(cols): x, y = a.cell(r % a.rows+1, c % a.cols+1), b.cell(r % b.rows+1, c % b.cols+1) if op == "&": value = _text(x) + _text(y) elif op in ("=", "!=", "<", ">", "<=", ">="): nx, ny = _num(x), _num(y) x, y = (nx, ny) if nx is not None and ny is not None else (_text(x).casefold(), _text(y).casefold()) value = {"=": lambda: x == y, "!=": lambda: x != y, "<": lambda: x < y, ">": lambda: x > y, "<=": lambda: x <= y, ">=": lambda: x >= y}[op]() else: x, y = int(x) if isinstance(x, bool) else _num(x), int(y) if isinstance(y, bool) else _num(y) if x is None or y is None: _diagnose(diagnostics, "bad_value"); return None if op == "/" and y == 0: _diagnose(diagnostics, "div_zero"); return None value = {"+": lambda: x+y, "-": lambda: x-y, "*": lambda: x*y, "/": lambda: x/y, "^": lambda: x**y}[op]() values.append(value) return Range(values, rows, cols) if isinstance(left, Range) or isinstance(right, Range) else values[0] def _english_sort_key(value): """English collation: letters before their accents, canonical accent ties stay stable. Case is ignored, matching Intl.Collator('en', {sensitivity:'accent'}). NFD makes composed/decomposed Latin accents identical without depending on the host locale. """ if isinstance(value, bool): return (2, int(value), ()) if isinstance(value, (int, float)): return (0, value, ()) if value is None: return (3, "", ()) text = unicodedata.normalize("NFD", str(value).casefold()) return (1, "".join(ch for ch in text if not unicodedata.combining(ch)), tuple((i, ord(ch)) for i, ch in enumerate(text) if unicodedata.combining(ch))) def _strict_num(v, diagnostics): """A SCALAR numeric argument to a wave-50 function. Text REFUSES; blank stays blank. ⛔ THIS IS NOT `_num`, AND IT MUST NOT BECOME IT. `_num` answers None for text, which is Excel's rule for a value inside a RANGE: SUM and COUNT skip the words and add the numbers, and `PARITY_FIXTURES["COUNT"]` has shipped on exactly that behaviour. A scalar argument is a different question. `CEILING("x", 2)` is not a request to round nothing, it is a mistake, and answering a number to it would hide the mistake inside a plausible total. """ if isinstance(v, Range): if len(v) != 1: _diagnose(diagnostics, "bad_value"); return None v = v.values[0] if v is None or (isinstance(v, str) and v == ""): return None n = _num(v) if n is None: _diagnose(diagnostics, "bad_value") return n def _compare_key(v): """An ordering key that keeps numbers with numbers and text with text, as Excel does.""" n = _num(v) if n is not None: return (0, n, "") return (1, 0.0, str("" if v is None else v).casefold()) def _values_equal(a, b): """Excel's own equality for a lookup: numeric when both are numbers, case-insensitive text.""" na, nb = _num(a), _num(b) if na is not None and nb is not None: return na == nb if (na is None) != (nb is None): return False return str("" if a is None else a).casefold() == str("" if b is None else b).casefold() def _wildcard_pattern(text): """Excel's `*` and `?` wildcards as a regex, with every other character taken literally.""" parts = [] for ch in text: if ch == "*": parts.append(".*") elif ch == "?": parts.append(".") else: parts.append(re.escape(ch)) return re.compile("".join(parts), re.IGNORECASE | re.DOTALL) _CRITERIA_OPS = (">=", "<=", "<>", ">", "<", "=") def _criteria_test(criterion): """One Excel criterion as a predicate over a cell value. Accepts a bare number, a bare text value matched without regard to case, and a string opening with `>`, `>=`, `<`, `<=`, `<>` or `=`. A text criterion may use the `*` and `?` wildcards. """ operator = "=" operand = criterion if isinstance(criterion, str): text = criterion.strip() for token in _CRITERIA_OPS: if text.startswith(token): operator, operand = token, text[len(token):].strip() break else: operand = text number = _num(operand) def test(value): if number is not None: left = _num(value) if left is None: return operator == "<>" return {">": left > number, ">=": left >= number, "<": left < number, "<=": left <= number, "=": left == number, "<>": left != number}[operator] if operator in ("=", "<>"): wanted = str("" if operand is None else operand) if "*" in wanted or "?" in wanted: hit = bool(_wildcard_pattern(wanted).fullmatch(str("" if value is None else value))) else: hit = _values_equal(value, operand) return hit if operator == "=" else not hit left, right = _compare_key(value), _compare_key(operand) return {">": left > right, ">=": left >= right, "<": left < right, "<=": left <= right}[operator] return test def _matching_rows(length, pairs, diagnostics): """Indices where every (criteria range, criterion) pair matches, or None on a length clash.""" for criteria_range, _ in pairs: if len(criteria_range) != length: # ⛔ REFUSE RATHER THAN ZIP SHORT. A criteria range one cell shorter than its value # range would otherwise answer a smaller total that looks entirely reasonable. _diagnose(diagnostics, "bad_value") return None tests = [(criteria_range, _criteria_test(criterion)) for criteria_range, criterion in pairs] return [i for i in range(length) if all(test(criteria_range.values[i]) for criteria_range, test in tests)] def _as_range(v): """Whatever arrived at a range position, as a `Range`.""" return v if isinstance(v, Range) else Range.scalar(v) def _snap(q): """Pull a quotient back onto an integer when binary floating point missed it by a hair.""" nearest = round(q) return float(nearest) if abs(q - nearest) < 1e-9 else q def _month_shift(d, months): """`d` moved by whole months, with the day clamped to the length of the target month.""" index = d.month - 1 + int(months) year, month = d.year + index // 12, index % 12 + 1 return dt.date(year, month, min(d.day, calendar.monthrange(year, month)[1])) def _holiday_dates(v): return {parsed for parsed in (_date(x) for x in _as_range(v)) if parsed} def _percentile(values, k): """Excel's inclusive PERCENTILE: linear interpolation between the neighbouring ranks.""" ordered = sorted(values) if not ordered or k is None or not 0 <= k <= 1: return None position = k * (len(ordered) - 1) low = math.floor(position) high = math.ceil(position) if low == high: return float(ordered[low]) return float(ordered[low] + (ordered[high] - ordered[low]) * (position - low)) def _cashflow_rate(values, times, guess, diagnostics): if (len(values) < 2 or not any(v < 0 for v in values) or not any(v > 0 for v in values) or guess <= -1 or any(t < 0 for t in times)): _diagnose(diagnostics, "numeric_error"); return None # This bounded Newton solver is a function algorithm, never workbook iteration. scale = max(abs(v) for v in values) rate = guess for _ in range(100): try: discount = [math.exp(-t * math.log1p(rate)) for t in times] value = math.fsum(v/scale*d for v, d in zip(values, discount)) derivative = math.fsum(-t*v/scale*d/(1+rate) for v, t, d in zip(values, times, discount)) except (ValueError, OverflowError): break if abs(value) < 1e-13: return rate if not derivative or not math.isfinite(derivative): break candidate = rate-value/derivative if candidate <= -1: candidate = (rate-1)/2 if not math.isfinite(candidate): break if abs(candidate-rate) < 1e-12 and abs(value) < 1e-9: return candidate rate = candidate _diagnose(diagnostics, "numeric_error") return None def _baht_text(number): digits = ("ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า") places = ("", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน") def spell(integer): if integer >= 1_000_000: high, low = divmod(integer, 1_000_000) return spell(high) + "ล้าน" + (spell(low) if low else "") text = "" for position in range(5, -1, -1): digit = integer // 10**position % 10 if not digit: continue word = "ยี่" if position == 1 and digit == 2 else "" if position == 1 and digit == 1 else "เอ็ด" if position == 0 and digit == 1 and integer > 10 else digits[digit] text += word + places[position] return text or digits[0] cents = int(Decimal(str(abs(number))).quantize(Decimal(".01"), rounding=ROUND_HALF_UP)*100) whole, fraction = divmod(cents, 100) return ("ลบ" if number < 0 else "") + spell(whole) + "บาท" + (spell(fraction) + "สตางค์" if fraction else "ถ้วน") def _call(fn, a, today, diagnostics=None): nums = [_num(x) for x in a]; present = [x for x in nums if x is not None] if fn in ("ADD", "MULTIPLY", "FV", "NORM.DIST", "BAHTTEXT"): numeric = [float(v) if isinstance(v, bool) else 0.0 if v is None else _num(v) for v in a] if any(v is None for v in numeric): _diagnose(diagnostics, "bad_value"); return None if fn == "ADD": return numeric[0]+numeric[1] if fn == "MULTIPLY": return numeric[0]*numeric[1] if fn == "BAHTTEXT": return _baht_text(numeric[0]) if fn == "FV": rate, nper, payment = numeric[:3] pv, when = numeric[3] if len(numeric) > 3 else 0, numeric[4] if len(numeric) > 4 else 0 if when not in (0, 1): _diagnose(diagnostics, "bad_value"); return None if rate == 0: return -(pv+payment*nper) growth = (1+rate)**nper if isinstance(growth, complex): _diagnose(diagnostics, "numeric_error"); return None return -(pv*growth+payment*(1+rate*when)*(growth-1)/rate) x, mean, sigma = numeric[:3] if sigma <= 0: _diagnose(diagnostics, "numeric_error"); return None z = (x-mean)/sigma return (math.erfc(-z/math.sqrt(2))/2 if _logical(a[3], diagnostics) else math.exp(-z*z/2)/(sigma*math.sqrt(2*math.pi))) if fn == "DATEDIF": start, end = _date(a[0]), _date(a[1]); unit = _text(a[2]).upper() if start is None or end is None: _diagnose(diagnostics, "bad_value"); return None if start > end or unit not in ("Y", "M", "D", "YM", "YD", "MD"): _diagnose(diagnostics, "numeric_error"); return None months = (end.year-start.year)*12+end.month-start.month-(end.day < start.day) if unit == "Y": return months//12 if unit == "M": return months if unit == "YM": return months % 12 if unit == "D": return (end-start).days if unit == "MD": # Excel's documented legacy MD algorithm can return a negative day count. return end.day-start.day+(calendar.monthrange(end.year if end.month > 1 else end.year-1, end.month-1 if end.month > 1 else 12)[1] if end.day < start.day else 0) year = end.year - ((end.month, end.day) < (start.month, start.day)) anniversary = dt.date(year, start.month, 1)+dt.timedelta(days=start.day-1) return (end-anniversary).days if fn in ("IRR", "XIRR"): raw = _as_range(a[0]).values values = [float(v) for v in raw if isinstance(v, (int, float)) and not isinstance(v, bool)] guess_at = 1 if fn == "IRR" else 2 guess = _num(a[guess_at]) if len(a) > guess_at else .1 if guess is None: _diagnose(diagnostics, "bad_value"); return None if fn == "IRR": return _cashflow_rate(values, range(len(values)), guess, diagnostics) dates = [_date(v) for v in _as_range(a[1]).values] if len(values) != len(dates) or any(v is None for v in dates): _diagnose(diagnostics, "numeric_error"); return None return _cashflow_rate(values, [(v-dates[0]).days/365 for v in dates], guess, diagnostics) if fn == "FILTER": array, include = _as_range(a[0]), _as_range(a[1]) vertical = include.cols == 1 and include.rows == array.rows horizontal = include.rows == 1 and include.cols == array.cols if not vertical and not horizontal: _diagnose(diagnostics, "bad_value"); return None if any(not isinstance(v, (bool, int, float)) and v is not None for v in include.values): _diagnose(diagnostics, "bad_value"); return None selected = [i+1 for i, value in enumerate(include.values) if value] if not selected: if len(a) == 3: return _as_range(a[2]) _diagnose(diagnostics, "empty_array"); return None rows = selected if vertical else range(1, array.rows+1) cols = range(1, array.cols+1) if vertical else selected return Range([array.cell(r, c) for r in rows for c in cols], len(rows), len(cols)) if fn == "SORT": array = _as_range(a[0]) index = _strict_num(a[1], diagnostics) if len(a) > 1 else 1 order = _strict_num(a[2], diagnostics) if len(a) > 2 else 1 by_col = a[3] if len(a) > 3 else False if not isinstance(by_col, bool) or index is None or int(index) != index or order not in (-1, 1): _diagnose(diagnostics, "bad_value"); return None span = array.rows if by_col else array.cols if not 1 <= index <= span: _diagnose(diagnostics, "bad_value"); return None indices = sorted(range(1, (array.cols if by_col else array.rows)+1), key=lambda i: _english_sort_key(array.cell(int(index), i) if by_col else array.cell(i, int(index))), reverse=order == -1) return Range([array.cell(r, c) for r in (range(1, array.rows+1) if by_col else indices) for c in (indices if by_col else range(1, array.cols+1))], array.rows, array.cols) if fn == "ABS": return abs(nums[0]) if nums[0] is not None else None if fn == "ROUND": return _round(a[0], a[1] if len(a) > 1 else 0) if fn == "ROUNDUP": n, p = nums[0], int(nums[1] or 0); return None if n is None else math.copysign(math.ceil(abs(n)*10**p)/10**p, n) if fn == "ROUNDDOWN": n, p = nums[0], int(nums[1] or 0); return None if n is None else math.copysign(math.floor(abs(n)*10**p)/10**p, n) if fn == "INT": return math.floor(nums[0]) if nums[0] is not None else None if fn == "MOD": return None if None in nums or nums[1] == 0 else nums[0] % nums[1] if fn == "SQRT": return math.sqrt(nums[0]) if nums[0] is not None and nums[0] >= 0 else None if fn == "POWER": return None if None in nums else nums[0] ** nums[1] if fn == "EXP": return math.exp(nums[0]) if nums[0] is not None else None if fn == "LN": return math.log(nums[0]) if nums[0] is not None and nums[0] > 0 else None if fn == "SUM": return sum(present) if fn == "AVERAGE": return sum(present)/len(present) if present else None if fn == "COUNT": return len(present) if fn == "COUNTA": return sum(x is not None and x != "" for x in a) if fn == "MIN": return min(present) if present else None if fn == "MAX": return max(present) if present else None if fn in ("AND", "OR"): if not all(isinstance(x, bool) for x in a): return None return all(a) if fn == "AND" else any(a) if fn == "NOT": return not a[0] if isinstance(a[0], bool) else None if fn == "ISBLANK": return a[0] is None or a[0] == "" if fn == "SWITCH": pairs = a[1:]; fallback = None if len(pairs) % 2: fallback = pairs.pop() for i in range(0, len(pairs), 2): if str(a[0]).casefold() == str(pairs[i]).casefold(): return pairs[i+1] return fallback if fn == "CONCATENATE": return "".join(_text(x) for x in a) if fn == "LEFT": return _text(a[0])[:int(nums[1] if len(a)>1 and nums[1] is not None else 1)] if fn == "RIGHT": return _text(a[0])[-int(nums[1] if len(a)>1 and nums[1] is not None else 1):] if fn == "MID": return _text(a[0])[max(0,int(nums[1] or 1)-1):max(0,int(nums[1] or 1)-1)+int(nums[2] or 0)] if fn == "LEN": return len(_text(a[0])) if fn == "TRIM": return " ".join(_text(a[0]).split()) if fn == "UPPER": return _text(a[0]).upper() if fn == "LOWER": return _text(a[0]).lower() if fn == "PROPER": return _text(a[0]).title() if fn == "VALUE": return _num(a[0]) if fn == "TEXT": n = _num(a[0]); fmt = str(a[1]); if n is None: return None if fmt == "0%": return f"{round(n*100):.0f}%" if fmt in ("0.00", "#,##0.00", "$#,##0.00"): return ("$" if fmt.startswith("$") else "") + f"{n:,.2f}" return None if fn == "SUBSTITUTE": text, old, new = map(_text, a[:3]) if len(a) == 3: return text.replace(old, new) occurrence = int(nums[3] or 0); parts = text.split(old) return old.join(parts[:occurrence]) + (new + old.join(parts[occurrence:]) if 0 < occurrence < len(parts) else "") if fn == "FIND": start = int(nums[2] or 1)-1 if len(a)>2 else 0; pos = _text(a[1]).find(_text(a[0]), start) return pos+1 if pos >= 0 else None if fn in ("REGEX_EXTRACT", "REGEX_REPLACE"): pattern, subject = _safe_regex(a[1], a[0]); m = re.search(pattern, subject) if fn == "REGEX_EXTRACT": return m.group(0) if m else None return re.sub(pattern, _text(a[2]), subject) if fn == "TODAY": return str(today)[:10] if fn in ("YEAR", "MONTH", "DAY"): d = _date(a[0]); return getattr(d, fn.lower()) if d else None if fn == "DAYS": x,y=_date(a[0]),_date(a[1]); return (x-y).days if x and y else None if fn == "DATEADD": d, n, unit = _date(a[0]), nums[1], _text(a[2]).lower() if not d or n is None: return None n=int(n) if unit in ("day","days"): d += dt.timedelta(days=n) elif unit in ("week","weeks"): d += dt.timedelta(weeks=n) elif unit in ("month","months"): month=d.month-1+n; year=d.year+month//12; month=month%12+1; d=d.replace(year=year,month=month,day=min(d.day,calendar.monthrange(year,month)[1])) elif unit in ("year","years"): d=d.replace(year=d.year+n,day=min(d.day,calendar.monthrange(d.year+n,d.month)[1])) else: return None return d.isoformat() if fn == "DATETIME_DIFF": x,y=_date(a[0]),_date(a[1]); unit=_text(a[2] if len(a)>2 else "days").lower() if not x or not y: return None days=(x-y).days return days if unit in ("day","days") else math.trunc(days/7) if unit in ("week","weeks") else None if fn == "DATETIME_FORMAT": d=_date(a[0]); fmt=_text(a[1]); if not d: return None tokens={"YYYY":f"{d.year:04d}","MM":f"{d.month:02d}","DD":f"{d.day:02d}","M":str(d.month),"D":str(d.day)} for key in sorted(tokens,key=len,reverse=True): fmt=fmt.replace(key,tokens[key]) return fmt # ══ wave 50, W50-T16: the Excel core ═════════════════════════════════════════════════════ # ⛔ EVERY SCALAR NUMERIC ARGUMENT BELOW GOES THROUGH `_strict_num`, NOT `_num`. Values read # out of a `Range` keep Excel's ignore-text rule; a scalar argument does not. See `_strict_num`. if fn in ("SUMIF", "AVERAGEIF"): # ⛔ THE SUM RANGE IS THE THIRD ARGUMENT AND IT IS OPTIONAL. With only two arguments the # criteria range is also the range being added, which is what Excel does. criteria_range = _as_range(a[0]) target = _as_range(a[2]) if len(a) > 2 else criteria_range matched = _matching_rows(len(target), [(criteria_range, a[1])], diagnostics) if matched is None: return None picked = [n for n in (_num(target.values[i]) for i in matched) if n is not None] if fn == "SUMIF": return float(sum(picked)) return sum(picked) / len(picked) if picked else None if fn in ("SUMIFS", "AVERAGEIFS", "MAXIFS", "MINIFS"): # ⛔ AND HERE THE RANGE BEING AGGREGATED COMES FIRST, followed by criteria range and # criterion in pairs. This is the opposite of SUMIF and it is the classic Excel mistake. target = _as_range(a[0]) pairs = [(_as_range(a[i]), a[i + 1]) for i in range(1, len(a) - 1, 2)] matched = _matching_rows(len(target), pairs, diagnostics) if matched is None: return None picked = [n for n in (_num(target.values[i]) for i in matched) if n is not None] if fn == "SUMIFS": return float(sum(picked)) if fn == "AVERAGEIFS": return sum(picked) / len(picked) if picked else None if not picked: return 0.0 return max(picked) if fn == "MAXIFS" else min(picked) if fn == "COUNTIF": criteria_range = _as_range(a[0]) matched = _matching_rows(len(criteria_range), [(criteria_range, a[1])], diagnostics) return None if matched is None else len(matched) if fn == "COUNTIFS": pairs = [(_as_range(a[i]), a[i + 1]) for i in range(0, len(a) - 1, 2)] if not pairs: _diagnose(diagnostics, "bad_value") return None matched = _matching_rows(len(pairs[0][0]), pairs, diagnostics) return None if matched is None else len(matched) if fn == "SUMPRODUCT": arrays = [_as_range(x) for x in a] width = len(arrays[0]) if any(len(one) != width for one in arrays): _diagnose(diagnostics, "bad_value") return None total = 0.0 for i in range(width): product = 1.0 for one in arrays: product *= _num(one.values[i]) or 0.0 total += product return total if fn == "COUNTBLANK": return sum(1 for value in _as_range(a[0]) if value is None or value == "") if fn in ("VLOOKUP", "HLOOKUP"): # ⛔ THE FOURTH ARGUMENT DEFAULTS TO TRUE, WHICH MEANS APPROXIMATE. That default is Excel's # and it is the commonest source of a wrong lookup, so both branches carry a fixture. table = _as_range(a[1]) offset = _strict_num(a[2], diagnostics) if offset is None: return None offset = int(offset) approximate = a[3] if len(a) > 3 else True if not isinstance(approximate, bool): _diagnose(diagnostics, "bad_value") return None vertical = fn == "VLOOKUP" count = table.rows if vertical else table.cols span = table.cols if vertical else table.rows if not 1 <= offset <= span: _diagnose(diagnostics, "bad_value") return None def probe(i): return table.cell(i, 1) if vertical else table.cell(1, i) hit = None if approximate: wanted = _compare_key(a[0]) for i in range(1, count + 1): if _compare_key(probe(i)) <= wanted: hit = i else: break else: for i in range(1, count + 1): if _values_equal(probe(i), a[0]): hit = i break if hit is None: _diagnose(diagnostics, "no_match") return None return table.cell(hit, offset) if vertical else table.cell(offset, hit) if fn == "XLOOKUP": lookup_array, return_array = _as_range(a[1]), _as_range(a[2]) vertical = lookup_array.cols == 1 if ((not vertical and lookup_array.rows != 1) or (lookup_array.rows != return_array.rows if vertical else lookup_array.cols != return_array.cols)): _diagnose(diagnostics, "bad_value") return None if isinstance(a[0], Range): wanted = a[0] pieces = [_call(fn, [value, *a[1:]], today, diagnostics) for value in wanted.values] if diagnostics: return None pieces = [_as_range(piece) for piece in pieces] if any((p.rows, p.cols) != (1, 1) for p in pieces): _diagnose(diagnostics, "bad_value"); return None return Range([p.values[0] for p in pieces], wanted.rows, wanted.cols) mode = 0 if len(a) > 4: mode = _strict_num(a[4], diagnostics) if mode is None: return None mode = int(mode) if mode not in (-1, 0, 1, 2): _diagnose(diagnostics, "bad_value"); return None hit = None for i, value in enumerate(lookup_array.values): if (bool(re.fullmatch(_wildcard_pattern(_text(a[0])), _text(value), re.I)) if mode == 2 else _values_equal(value, a[0])): hit = i break if hit is None and mode in (-1, 1): wanted = _compare_key(a[0]) for i, value in enumerate(lookup_array.values): key = _compare_key(value) if mode == -1 and key <= wanted and ( hit is None or key > _compare_key(lookup_array.values[hit])): hit = i if mode == 1 and key >= wanted and ( hit is None or key < _compare_key(lookup_array.values[hit])): hit = i if hit is None: if len(a) > 3 and a[3] is not None: return a[3] _diagnose(diagnostics, "no_match") return None values = ([return_array.cell(hit+1, c) for c in range(1, return_array.cols+1)] if vertical else [return_array.cell(r, hit+1) for r in range(1, return_array.rows+1)]) return values[0] if len(values) == 1 else Range(values, 1 if vertical else return_array.rows, return_array.cols if vertical else 1) if fn == "INDEX": array = _as_range(a[0]) first = _strict_num(a[1], diagnostics) if first is None: return None if len(a) > 2: second = _strict_num(a[2], diagnostics) if second is None: return None wanted_row, wanted_col = int(first), int(second) elif array.rows == 1: wanted_row, wanted_col = 1, int(first) elif array.cols == 1: wanted_row, wanted_col = int(first), 1 else: wanted_row, wanted_col = int(first), 0 if not (0 <= wanted_row <= array.rows and 0 <= wanted_col <= array.cols): _diagnose(diagnostics, "bad_value") return None if wanted_row == 0 or wanted_col == 0: rows = [wanted_row] if wanted_row else range(1, array.rows+1) cols = [wanted_col] if wanted_col else range(1, array.cols+1) return Range([array.cell(r, c) for r in rows for c in cols], len(rows), len(cols)) return array.cell(wanted_row, wanted_col) if fn == "MATCH": array = _as_range(a[1]) mode = 1 if len(a) > 2: mode = _strict_num(a[2], diagnostics) if mode is None: return None mode = int(mode) wanted = _compare_key(a[0]) hit = None for i, value in enumerate(array.values): if mode == 0: if _values_equal(value, a[0]): hit = i + 1 break elif mode == 1: # Ascending: keep taking while the value is still at or below the target. if _compare_key(value) <= wanted: hit = i + 1 else: break else: if _compare_key(value) >= wanted: hit = i + 1 else: break if hit is None: _diagnose(diagnostics, "no_match") return None return hit if fn == "CHOOSE": offset = _strict_num(a[0], diagnostics) if offset is None: return None offset = int(offset) if not 1 <= offset < len(a): _diagnose(diagnostics, "bad_value") return None return a[offset] if fn in ("ROW", "COLUMN"): try: column, row_number = _split_addr(str(a[0] or "").rsplit("!", 1)[-1]) except FormulaError: _diagnose(diagnostics, "bad_value") return None return row_number if fn == "ROW" else col_to_index(column) if fn in ("ROWS", "COLUMNS"): target = _as_range(a[0]) return target.rows if fn == "ROWS" else target.cols if fn == "XOR": if not all(isinstance(x, bool) for x in a): return None return sum(1 for x in a if x) % 2 == 1 if fn == "RANK": number = _strict_num(a[0], diagnostics) if number is None: return None order = 0 if len(a) > 2: order = _strict_num(a[2], diagnostics) if order is None: return None pool = [n for n in (_num(value) for value in _as_range(a[1])) if n is not None] if number not in pool: _diagnose(diagnostics, "no_match") return None if order: return sum(1 for n in pool if n < number) + 1 return sum(1 for n in pool if n > number) + 1 if fn == "MEDIAN": if not present: return None ordered = sorted(present) middle = len(ordered) // 2 if len(ordered) % 2: return float(ordered[middle]) return (ordered[middle - 1] + ordered[middle]) / 2 if fn in ("VAR", "VAR.P", "STDEV", "STDEV.P"): # A sample estimate divides by n minus 1 and needs at least two numbers; a population # figure divides by n. That single character is the whole difference between the names. sample = fn in ("VAR", "STDEV") if len(present) < (2 if sample else 1): return None mean = sum(present) / len(present) spread = sum((n - mean) ** 2 for n in present) variance = spread / ((len(present) - 1) if sample else len(present)) return variance if fn.startswith("VAR") else math.sqrt(variance) if fn in ("PERCENTILE", "QUARTILE"): pool = [n for n in (_num(value) for value in _as_range(a[0])) if n is not None] k = _strict_num(a[1], diagnostics) if k is None: return None if fn == "QUARTILE": if not 0 <= k <= 4: _diagnose(diagnostics, "bad_value") return None k = k / 4.0 answer = _percentile(pool, k) if answer is None: _diagnose(diagnostics, "bad_value") return answer if fn in ("LARGE", "SMALL"): pool = sorted(n for n in (_num(value) for value in _as_range(a[0])) if n is not None) k = _strict_num(a[1], diagnostics) if k is None: return None k = int(k) if not 1 <= k <= len(pool): _diagnose(diagnostics, "bad_value") return None return float(pool[-k] if fn == "LARGE" else pool[k - 1]) if fn == "AVERAGEA": # ⚠ AVERAGEA IS THE ONE FUNCTION THAT COUNTS TEXT RATHER THAN SKIPPING IT, reading it as # zero, which is the whole reason Excel gives it a separate name from AVERAGE. counted = [x for x in a if x is not None and x != ""] if not counted: return None total = 0.0 for x in counted: if isinstance(x, bool): total += 1.0 if x else 0.0 else: total += _num(x) or 0.0 return total / len(counted) if fn in ("CEILING", "FLOOR", "MROUND"): number = _strict_num(a[0], diagnostics) step = _strict_num(a[1], diagnostics) if number is None or step is None: return None if step == 0: return 0.0 if fn == "MROUND" else None quotient = _snap(number / step) if fn == "CEILING": return math.ceil(quotient) * step if fn == "FLOOR": return math.floor(quotient) * step return float(Decimal(str(quotient)).quantize(Decimal("1"), rounding=ROUND_HALF_UP)) * step if fn == "PRODUCT": if not present: return 0.0 total = 1.0 for n in present: total *= n return total if fn in ("EOMONTH", "EDATE"): d, months = _date(a[0]), _strict_num(a[1], diagnostics) if d is None or months is None: return None shifted = _month_shift(d, int(months)) if fn == "EDATE": return shifted.isoformat() return shifted.replace( day=calendar.monthrange(shifted.year, shifted.month)[1]).isoformat() if fn == "WEEKDAY": d = _date(a[0]) kind = 1 if len(a) > 1: kind = _strict_num(a[1], diagnostics) if kind is None: return None kind = int(kind) if d is None: return None monday_based = d.weekday() # Monday is 0 here, Sunday is 6 if kind == 1: return (monday_based + 1) % 7 + 1 if kind == 2: return monday_based + 1 if kind == 3: return monday_based _diagnose(diagnostics, "bad_value") return None if fn == "WEEKNUM": d = _date(a[0]) kind = 1 if len(a) > 1: kind = _strict_num(a[1], diagnostics) if kind is None: return None kind = int(kind) if d is None: return None if kind not in (1, 2): _diagnose(diagnostics, "bad_value") return None # Return type 1 begins the week on Sunday, return type 2 on Monday. The offset is how far # January 1 already sits into its own week, which is what shifts the boundary. first = dt.date(d.year, 1, 1) offset = (first.weekday() + 1) % 7 if kind == 1 else first.weekday() return ((d - first).days + offset) // 7 + 1 if fn == "NETWORKDAYS": start, end = _date(a[0]), _date(a[1]) if start is None or end is None: return None if abs((end - start).days) > MAX_DAY_SPAN: _diagnose(diagnostics, "bad_value") return None holidays = _holiday_dates(a[2]) if len(a) > 2 else set() step = 1 if end >= start else -1 counted, cursor = 0, start while True: if cursor.weekday() < 5 and cursor not in holidays: counted += 1 if cursor == end: break cursor += dt.timedelta(days=step) return counted if step == 1 else -counted if fn == "WORKDAY": start, days = _date(a[0]), _strict_num(a[1], diagnostics) if start is None or days is None: return None days = int(days) if abs(days) > MAX_DAY_SPAN: _diagnose(diagnostics, "bad_value") return None holidays = _holiday_dates(a[2]) if len(a) > 2 else set() step = 1 if days >= 0 else -1 cursor, remaining = start, abs(days) while remaining: cursor += dt.timedelta(days=step) if cursor.weekday() < 5 and cursor not in holidays: remaining -= 1 return cursor.isoformat() if fn == "DATE": parts = [_strict_num(x, diagnostics) for x in a[:3]] if any(part is None for part in parts): return None year, month, day = (int(part) for part in parts) # Excel rolls an out of range month or day into the neighbouring year or month rather than # refusing, so DATE(2024, 13, 1) is January 2025. year += (month - 1) // 12 month = (month - 1) % 12 + 1 try: return (dt.date(year, month, 1) + dt.timedelta(days=day - 1)).isoformat() except (ValueError, OverflowError): _diagnose(diagnostics, "bad_value") return None if fn == "DATEVALUE": # ⚠ THIS RETURNS THE NORMALIZED ISO DATE, NOT A SERIAL NUMBER. Excel's DATEVALUE answers # the day count since 1900 because a date IS a number there. This engine's date type is the # ISO string, so the honest answer is that string; inventing a serial would create a second # date representation that nothing else in the file reads. d = _date(a[0]) if d is None: _diagnose(diagnostics, "bad_value") return None return d.isoformat() if fn == "NOW": # ⚠ THE CLOCK OF THIS ENGINE IS THE `today` IT WAS HANDED, and its resolution stops there. # A real wall clock would make NOW() untestable: no fixture could name its answer, and the # browser and the server would disagree by however long the request took. return f"{str(today)[:10]} 00:00:00" if fn in ("HOUR", "MINUTE"): found = re.search(r"([01]?[0-9]|2[0-3]):([0-5][0-9])", _text(a[0])) if found: return int(found.group(1)) if fn == "HOUR" else int(found.group(2)) if _date(a[0]) is not None: return 0 _diagnose(diagnostics, "bad_value") return None if fn == "TEXTJOIN": if not isinstance(a[1], bool): _diagnose(diagnostics, "bad_value") return None parts = [_text(x) for x in a[2:]] if a[1]: parts = [part for part in parts if part != ""] return _text(a[0]).join(parts) if fn == "REPT": text = _text(a[0]) times = _strict_num(a[1], diagnostics) if times is None: return None times = int(times) if times < 0 or len(text) * times > MAX_TEXT_RESULT: _diagnose(diagnostics, "bad_value") return None return text * times if fn == "EXACT": # ⛔ EXACT MATCHES CASE AND `=` DOES NOT. `_eval`'s comparison folds case deliberately, # which is Excel's rule for the operator, so EXACT is the only way to ask the strict # question and it must not be routed through the same helper. return _text(a[0]) == _text(a[1]) if fn == "ISNUMBER": # ⚠ THE PYTHON TYPE DECIDES, NOT `_num`. `ISNUMBER("12")` is FALSE in Excel: the cell holds # text that looks like a number, and saying otherwise would make the function useless for # the one job it has, which is telling those two apart. return isinstance(a[0], (int, float)) and not isinstance(a[0], bool) if fn == "ISTEXT": return isinstance(a[0], str) raise FormulaError("formula function is not implemented") def explain_recalculation(definition, field_revisions): """Compact provenance; formula history stores definitions, never redundant cell snapshots.""" definition = definition if isinstance(definition, dict) else {} field_revisions = field_revisions if isinstance(field_revisions, dict) else {} canonical = {key: definition.get(key) for key in ("version", "source", "ast", "refs")} digest = hashlib.sha256(json.dumps( canonical, sort_keys=True, separators=(",", ":"), ensure_ascii=False ).encode("utf-8")).hexdigest() def revision(value, default): if isinstance(value, bool): return default try: return max(0, int(value)) except (TypeError, ValueError, OverflowError): return default return {"formulaRevision": revision(definition.get("revision"), 1) or 1, "astVersion": revision(definition.get("version"), AST_VERSION) or AST_VERSION, "definitionHash": f"sha256:{digest}", "inputs": {key: revision(field_revisions.get(key), 0) for key in definition.get("refs") or ()}, "valueSnapshotStored": False} def evaluate_fields(definitions, row, *, today=None): """Evaluate formula-over-formula dependencies once, refusing every member of a cycle.""" definitions = definitions if isinstance(definitions, dict) else {} row = row if isinstance(row, dict) else {} # Stored/client materialisations are never authority. A definition present in this batch # always replaces a same-named row value through the server evaluator. values = {key: value for key, value in row.items() if key not in definitions} errors, active, resolved = {}, [], set() def resolve(key): if key in resolved or (key in values and key not in definitions): return values[key] if key in active: start = active.index(key) for member in active[start:]: errors[member] = "cycle" values[member] = None return None definition = definitions.get(key) if not isinstance(definition, dict): return None active.append(key) inputs = dict(values) dependency_error = False for ref in definition.get("refs") or (): if ref in definitions: inputs[ref] = resolve(ref) dependency_error = dependency_error or ref in errors elif ref in row: inputs[ref] = row[ref] if errors.get(key) == "cycle": active.pop() resolved.add(key) return None result = evaluate_result(definition, inputs, today=today) active.pop() values[key] = result["value"] if result["error"]: errors[key] = ("dependency_error" if result["error"] == "blank" and dependency_error else result["error"]) resolved.add(key) return values.get(key) for field_key in definitions: resolve(field_key) return {"values": {key: values.get(key) for key in definitions}, "errors": errors} def _sheet_half(key): """The tab a lookup key names, upper cased, or "" when the key is a bare address.""" text = str(key) return text.rsplit("!", 1)[0].upper() if "!" in text else "" def _unknown_sheets(definition, known): """Every tab this formula points at that the workbook does not have, in the order found. ⛔ IT WALKS `definition["cells"]`, NOT THE EVALUATOR'S NODE LOOKUP, AND THAT IS THE POINT. `_range_arg` treats a key missing from `row` as a BLANK CELL on purpose, because a rectangle almost always contains empty cells; so a check living in the lookup would catch `='Ghost'!A1` and let `=SUM('Ghost'!A1:B9)` answer a confident 0. `cells` carries every address a formula names, scalar and range alike, so one walk covers both. """ out = [] for key in definition.get("cells") or (): name = _sheet_half(key) if name and name not in known and name not in out: out.append(name) return out def _range_bounds(first, last, sheet=""): a, ar = _split_addr(first) b, br = _split_addr(last) ac, bc = col_to_index(a), col_to_index(b) return (str(sheet).upper(), min(ac, bc), max(ac, bc), min(ar, br), max(ar, br)) _BAND_SCAN = re.compile( r'"(?:[^"]|"")*"|\'(?:[^\']|\'\')*\'(?!\!)|' r"(?(?:(?:'[^']{1,64}'|[A-Za-z_][A-Za-z0-9_]{0,63})!)?)" r"\$?(?P[A-Za-z]{1,3}|[1-9][0-9]{0,6}):\$?(?P[A-Za-z]{1,3}|[1-9][0-9]{0,6})" r"(?![A-Za-z0-9_$!])") def _expand_bands(source): """Normalize whole bands to bounded Excel rectangles, without expanding any cells.""" def replace(match): first, last = match.group("first"), match.group("last") if not first or first.isalpha() != last.isalpha(): return match.group(0) ends = (first + "1:" + last + "1048576" if first.isalpha() else "A" + first + ":XFD" + last) return match.group("prefix") + ends return _BAND_SCAN.sub(replace, source) def _address_parts(key): sheet, _, addr = str(key).rpartition("!") col, row = _split_addr(addr) return sheet.upper(), col_to_index(col), row def _segments(lo, hi): """Canonical dyadic cover. A million-row band takes one subscription, not a million.""" lo -= 1 while lo < hi: width = (lo & -lo) if lo else 1 << (hi.bit_length() - 1) while width > hi - lo: width >>= 1 yield width.bit_length() - 1, lo // width lo += width class _RangeIndex: def __init__(self): self.buckets, self.owned = {}, {} self.levels = {} def add(self, owner, bounds): sheet, c0, c1, r0, r1 = bounds for cl, ci in _segments(c0, c1): for rl, ri in _segments(r0, r1): token = (sheet, cl, ci, rl, ri) if token not in self.buckets: levels = self.levels.setdefault(sheet, {}) levels[cl, rl] = levels.get((cl, rl), 0) + 1 self.buckets.setdefault(token, set()).add(owner) self.owned.setdefault(owner, set()).add(token) def remove(self, owner): for token in self.owned.pop(owner, ()): self.buckets[token].discard(owner) if not self.buckets[token]: del self.buckets[token] sheet, cl, _, rl, _ = token levels = self.levels[sheet] levels[cl, rl] -= 1 if not levels[cl, rl]: del levels[cl, rl] if not levels: del self.levels[sheet] def at(self, key, stats): sheet, col, row = _address_parts(key) out = set() for cl, rl in self.levels.get(sheet, ()): stats["range_probes"] += 1 hits = self.buckets.get((sheet, cl, (col - 1) >> cl, rl, (row - 1) >> rl), ()) stats["range_checks"] += len(hits) out.update(hits) return out class _SparseCells: """Sorted populated coordinates; range queries never inspect unrelated cells or formulas.""" def __init__(self): self.columns, self.rows = {}, {} def add(self, key): sheet, col, row = _address_parts(key) cols = self.columns.setdefault(sheet, []) rows = self.rows.get((sheet, col)) if rows is None: insort(cols, col) rows = self.rows[(sheet, col)] = [] at = bisect_left(rows, row) if at == len(rows) or rows[at] != row: rows.insert(at, row) def remove(self, key): sheet, col, row = _address_parts(key) rows = self.rows.get((sheet, col), []) at = bisect_left(rows, row) if at < len(rows) and rows[at] == row: rows.pop(at) if not rows and (sheet, col) in self.rows: del self.rows[sheet, col] self.columns[sheet].remove(col) def within(self, bounds): sheet, c0, c1, r0, r1 = bounds cols = self.columns.get(sheet, []) found = [] for col in cols[bisect_left(cols, c0):bisect_right(cols, c1)]: rows = self.rows[sheet, col] found.extend((row, col) for row in rows[bisect_left(rows, r0):bisect_right(rows, r1)]) for row, col in sorted(found): yield a1_key(index_to_col(col) + str(row), sheet) class _SheetInputs(dict): def __init__(self, engine, address): super().__init__({SHEET_ADDR_KEY: address}) self.engine = engine self.ignore_reference_errors = 0 self.format_stack = [] self.last_format = None def __contains__(self, key): return True # Missing Sheet cells are blanks, as in the existing evaluate_sheet DTO. def get(self, key, default=None): if key == SHEET_ADDR_KEY: return super().get(key, default) self.engine._consume(super().get(SHEET_ADDR_KEY), key) owner = self.engine.spill_parents.get(key) if owner in self.engine._pending: raise _NeedReference(owner) fault = key if key in self.engine.errors else None if not _occupied(self.engine.specs.get(key)): producers = self.engine.prospective.at(key, self.engine.stats) pending = producers & self.engine._pending if pending: raise _NeedReference(sorted(pending)[0]) fault = next((ref for ref in sorted(producers) if self.engine.errors.get(ref) == "circular_reference"), fault) if key in self.engine._pending: raise _NeedReference(key) if fault: if self.ignore_reference_errors: return "#ERROR!" raise _ReferenceFault(fault) self.engine.stats["reads"] += 1 if self.format_stack: self.format_stack[-1].append(self.engine.formats.get(key)) return self.engine.values.get(key, default) def range_values(self, bounds): # A sparse range must settle potential producers before deciding which cells exist. for key in self.engine.array_positions.within(bounds): if key in self.engine._pending: raise _NeedReference(key) for key in self.engine.array_roots: if key not in self.engine._pending: continue area = self.engine.prospective_bounds.get(key) if area and area[0] == bounds[0] and max(area[1], bounds[1]) <= min(area[2], bounds[2]) and max(area[3], bounds[3]) <= min(area[4], bounds[4]): raise _NeedReference(key) return [self.get(key) for key in self.engine.positions.within(bounds)] def _spill_marker(spec, key): marker = (spec.get("formulaMeta") or {}).get("spillChild") if isinstance(spec, dict) else None return (marker if isinstance(marker, dict) and marker.get("version") == 1 and marker.get("address") == key and isinstance(marker.get("origin"), str) and _is_a1_key(marker["origin"]) and _sheet_half(marker["origin"]) == _sheet_half(key) and marker["origin"] != key and spec.get("kind") != "formula" else None) def _occupied(spec): if not isinstance(spec, dict): return spec is not None if spec.get("kind") == "empty": return False return (spec.get("kind") in ("formula", "bound", "binding") or bool(spec.get("formula")) or spec.get("binding") is not None or spec.get("value") is not None or spec.get("text") is not None or bool(spec.get("refused"))) @lru_cache(maxsize=8192) def _static_reference_shape(text): return _array_shape(_sheet_syntax(text, "")) def _array_shape(node, lookup=None, seen=()): """Conservative output extent, independent of values; scalars never reserve children.""" kind, args = node.get("t"), node.get("args", []) if kind == "a1range": return (node["rows"], node["cols"]) shape = lambda child: _array_shape(child, lookup, seen) if kind in ("name", "neg"): return shape(node["e"]) if kind == "spill" and lookup and node["e"].get("t") == "a1": key = node["e"]["k"] target = lookup(key) if target and key not in seen: return _array_shape(target, lookup, (*seen, key)) if kind in ("bin", "cmp"): a, b = shape(node["l"]), shape(node["r"]) return max(a[0], b[0]), max(a[1], b[1]) if kind == "call": fn = node["fn"] if fn in ("SORT", "FILTER"): return shape(args[0]) if fn == "INDIRECT" and args[0].get("t") == "const" and isinstance(args[0].get("v"), str): try: return _static_reference_shape(args[0]["v"]) except FormulaError: return 1, 1 if fn == "OFFSET": rows, cols = shape(args[0]) def dimension(index, default): value = args[index].get("v") if len(args) > index else None return max(1, int(value)) if isinstance(value, (int, float)) and math.isfinite(value) else default return dimension(3, rows), dimension(4, cols) if fn == "IF": shapes = [shape(arg) for arg in args[1:]] return max(s[0] for s in shapes), max(s[1] for s in shapes) if fn in ("IFERROR", "IFNA"): a, b = [shape(arg) for arg in args]; return max(a[0], b[0]), max(a[1], b[1]) if fn == "XLOOKUP": source, result = shape(args[1]), shape(args[2]) wanted = shape(args[0]) return wanted if wanted[0]*wanted[1] > 1 else (1, result[1]) if source[1] == 1 else (result[0], 1) if fn == "INDEX": rows, cols = shape(args[0]) r = args[1].get("v") c = args[2].get("v") if len(args) > 2 else 0 if rows > 1 and cols > 1 else 1 return (rows if r == 0 else 1, cols if c == 0 else 1) return 1, 1 def _dynamic_array_shape(node): if node.get("t") == "call": args = node.get("args", []) if node["fn"] == "INDIRECT" and args[0].get("t") != "const": return True if node["fn"] == "OFFSET" and any(arg.get("t") != "const" for arg in args[3:]): return True return any(_dynamic_array_shape(arg) for arg in args) return any(_dynamic_array_shape(node[k]) for k in ("e", "l", "r") if isinstance(node.get(k), dict)) def _calculation_stats(): return dict(compiled=0, evaluated=0, visited=0, scanned=0, edges=0, range_checks=0, range_probes=0, reads=0) class _NeedReference(Exception): pass class _ReferenceFault(Exception): pass def _cyclic_components(nodes, reads): """Iterative Kosaraju: cycle members only, linear in the affected graph.""" seen, finished = set(), [] reverse = {} for key in nodes: for ref in reads.get(key, ()): if ref in nodes: reverse.setdefault(ref, []).append(key) for root in sorted(nodes): if root in seen: continue seen.add(root); stack = [(root, iter(sorted(set(reads.get(root, ())) & nodes)))] while stack: key, children = stack[-1] ref = next(children, None) if ref is None: finished.append(key); stack.pop() elif ref not in seen: seen.add(ref); stack.append((ref, iter(sorted(set(reads.get(ref, ())) & nodes)))) seen, components = set(), [] for root in reversed(finished): if root in seen: continue stack, members = [root], []; seen.add(root) while stack: key = stack.pop(); members.append(key) for ref in reverse.get(key, ()): if ref not in seen: seen.add(ref); stack.append(ref) if len(members) > 1 or root in reads.get(root, ()): components.append(sorted(members)) return sorted(components) class SheetCalculation: """C8 graph contract: ordered scalar/rectangle precedents, reverse subscriptions, revision. A reset visits the sparse snapshot once. An update visits only supplied cells and the reachable subgraph, including range consumers of newly populated or deleted addresses. Result dictionaries are owned by this instance; callers must not mutate them. """ def __init__(self, cells, *, revision=0, sheets=None, today=None, named_ranges=(), date_system="1900"): self.revision = revision self.sheets = None if sheets is None else {str(s).upper() for s in sheets} self.today = today self.named_ranges = _normalize_named_ranges(named_ranges) self._reference_syntax_cache = OrderedDict() self.date_system = date_system self.volatile_roots, self._pending = set(), set() self._volatile_values = {} self._clock = dt.datetime.now(dt.timezone.utc) self.stats = _calculation_stats() self.specs, self.compiled, self.values, self.errors, self.provenance = {}, {}, {}, {}, {} self.formats = {} self.reads, self.read_by = {}, {} self.consumed, self.consumed_by = {}, {} self.ranges, self.positions, self.formula_positions = _RangeIndex(), _SparseCells(), _SparseCells() self.spills, self.spill_parents, self.cleared_spills = {}, {}, {} self.prospective, self.prospective_bounds = _RangeIndex(), {} self.array_roots, self.array_positions = set(), _SparseCells() for key, spec in (cells or {}).items(): marker = _spill_marker(spec, str(key).upper()) if marker: self.cleared_spills[str(key).upper()] = marker["origin"] base = marker.get("base") if isinstance(base, dict) and not _occupied(base): self._put(str(key).upper(), base) continue self._put(str(key).upper(), spec) for key in self.compiled: self._connect(key) self._calculate(set(self.compiled)) def _put(self, key, spec): self.stats["scanned"] += 1 self.errors.pop(key, None) self.provenance.pop(key, None) self.formats.pop(key, None) if spec is None: self.specs.pop(key, None) self.values.pop(key, None) self.positions.remove(key) return spec = dict(spec) if isinstance(spec, dict) else {"value": spec} self.specs[key] = spec fmt = (spec.get("style") or {}).get("format") inferred = (spec.get("formulaMeta") or {}).get("inferredFormat") if fmt and not (isinstance(inferred, dict) and inferred.get("version") == 1 and inferred.get("format") == fmt): self.formats[key] = fmt self.positions.add(key) self.values[key] = spec.get("value") if spec.get("refused"): self._error(key, str(spec["refused"])) return source = spec.get("formula") if not isinstance(source, str) or not source.strip().startswith("="): return self.stats["compiled"] += 1 try: definition = parse_formula(source.strip()[1:], sheet=spec.get("sheet") or "", compact_ranges=True, named_ranges=self.named_ranges, address=key) except FormulaError: self._error(key, "bad_formula") return names = [_sheet_half(ref) for ref in definition["cells"]] names.extend(bounds[0] for bounds in definition["ranges"]) if self.sheets is not None and any(name and name not in self.sheets for name in names): self._error(key, "unknown_sheet") return self.compiled[key] = definition definition["dynamic_array_shape"] = _dynamic_array_shape(definition["ast"]) rows, cols = _array_shape(definition["ast"]) if rows*cols > 1: s, c, r = _address_parts(key) bounds = (s, c, min(16384, c+cols-1), r, min(1048576, r+rows-1)) self.prospective.add(key, bounds); self.prospective_bounds[key] = bounds self.array_roots.add(key); self.array_positions.add(key) if definition["volatile"]: self.volatile_roots.add(key) self.formula_positions.add(key) def reference_syntax(self, text, sheet, address): # Relative named definitions depend on the calling cell. Ordinary A1 reference # text depends only on its sheet; literal R1C1 offsets were resolved by the caller. key = (text, sheet, address if self.named_ranges else "") if key not in self._reference_syntax_cache: self._reference_syntax_cache[key] = _sheet_syntax(text, sheet, self.named_ranges, address=address) if len(self._reference_syntax_cache) > 8192: self._reference_syntax_cache.popitem(last=False) else: self._reference_syntax_cache.move_to_end(key) return self._reference_syntax_cache[key] def volatile_value(self, node, fn): token = id(node) if token not in self._volatile_values: now = dt.datetime.fromisoformat(str(self.today)) if self.today else self._clock.replace(tzinfo=None) # Formula dates have one representation in this runtime: ISO, the same representation # imported date literals, DATE/DATEVALUE, filters and the cell display path consume. # The old document graph special-cased volatile dates as Excel serials while the # compatibility evaluator returned ISO, so TODAY() could render as 46284 while # DATE(...) beside it rendered 2026-09-19. dateSystem still governs imported Excel # serial conversion at the input boundary; it must not create a second stored value # type after that conversion. self._volatile_values[token] = ( random.random() if fn == "RAND" else now.strftime("%Y-%m-%d %H:%M:%S") if fn == "NOW" else now.date().isoformat()) return self._volatile_values[token] def _connect(self, key): definition = self.compiled[key] self._index_array(key) deps = set(definition["cells"]) for bounds in definition["ranges"]: self.ranges.add(key, bounds) deps.update(self.formula_positions.within(bounds)) self.reads[key] = deps for ref in deps: self.read_by.setdefault(ref, set()).add(key) self.stats["edges"] += 1 def _index_array(self, key): rows, cols = _array_shape(self.compiled[key]["ast"], lambda ref: self.compiled.get(ref, {}).get("ast"), (key,)) self.prospective.remove(key); self.prospective_bounds.pop(key, None); self.array_roots.discard(key) if rows*cols > 1: s, c, r = _address_parts(key) area = (s, c, min(16384, c+cols-1), r, min(1048576, r+rows-1)) self.prospective.add(key, area); self.prospective_bounds[key] = area; self.array_roots.add(key) if self.compiled[key].get("dynamic_array_shape"): self.array_roots.add(key); self.array_positions.add(key) def _disconnect(self, key): self._forget_consumed(key) self.prospective.remove(key); self.prospective_bounds.pop(key, None) self.array_roots.discard(key); self.array_positions.remove(key) self.volatile_roots.discard(key) for ref in self.reads.pop(key, ()): self.read_by[ref].discard(key) if not self.read_by[ref]: del self.read_by[ref] self.ranges.remove(key) self.compiled.pop(key, None) self.formula_positions.remove(key) def _forget_consumed(self, key): for ref in self.consumed.pop(key, ()): owners = self.consumed_by[ref]; owners.discard(key) if not owners: del self.consumed_by[ref] def _consume(self, key, ref): refs = self.consumed.setdefault(key, set()) if ref not in refs: refs.add(ref); self.consumed_by.setdefault(ref, set()).add(key) def _spill_cycle(self, key, children): # A newly discovered child closes a dependency through its producer. Only # consumed references participate: an unused branch cannot create this edge. # Walk the producer's precedents, never the workbook or all range subscribers. if not any(self.consumed_by.get(child) for child in children): return False targets, reachable, edges, queue = set(children), {key}, {}, [key] for current in queue: deps = set() for ref in self.consumed.get(current, ()): owner = key if ref in targets else self.spill_parents.get(ref, ref) if owner in self.compiled: deps.add(owner) if owner not in reachable: reachable.add(owner); queue.append(owner) edges[current] = deps component = next((members for members in _cyclic_components(reachable, edges) if key in members), None) if not component: return False self._pass_cyclic.update(component) for member in component: self._error(member, "circular_reference"); self._pending.discard(member) self.provenance[member].update(origin=component[0], via=None, path=component) self.formats.pop(member, None) # Earlier consumers can already hold scalars. A graph refusal invalidates # those descendants once; they evaluate normally so IFERROR still catches. queue, seen = [*component, *children], set(component) | set(children) for ref in queue: for owner in self.read_by.get(ref, set()) | self.consumed_by.get(ref, set()) | self.ranges.at(ref, self.stats): if owner in seen or owner in self._pass_cyclic: continue seen.add(owner); queue.append(owner) if owner in self.compiled: if owner not in self._pass_dirty: self.stats["visited"] += 1 self._pass_dirty.add(owner); self._pending.add(owner) return True def _error(self, key, code, upstream=None): self._clear_spill(key) self.values[key] = None self.errors[key] = code trace = self.provenance.get(upstream) if upstream else None self.provenance[key] = {"code": code, "origin": trace["origin"] if trace else key, "via": upstream} def _clear_spill(self, key): previous = self.spills.pop(key, None) if not previous: return for child in previous["children"]: if self.spill_parents.get(child) != key: continue self.spill_parents.pop(child, None) self.formats.pop(child, None) # Replacing an owned output with an authored literal retires ownership, # but must not send a clear for that newly authored cell. if not _occupied(self.specs.get(child)): self.cleared_spills[child] = key if child not in self.specs: self.values.pop(child, None); self.positions.remove(child) else: self.values[child] = self.specs[child].get("value") fmt = (self.specs[child].get("style") or {}).get("format") if fmt: self.formats[child] = fmt def _publish(self, key, value): self._clear_spill(key) if not isinstance(value, Range): self.values[key] = value; return s, c, r = _address_parts(key) if r+value.rows-1 > 1048576 or c+value.cols-1 > 16384 or len(value) > MAX_RANGE_CELLS: self._error(key, "spill_obstructed"); return children = [a1_key(index_to_col(c+dc)+str(r+dr), s) for dr in range(value.rows) for dc in range(value.cols)] if any(_occupied(self.specs.get(child)) or child in self.spill_parents for child in children[1:]): self._error(key, "spill_obstructed"); return if self._spill_cycle(key, children[1:]): bounds = (s, c, c+value.cols-1, r, r+value.rows-1) self.prospective.add(key, bounds); self.prospective_bounds[key] = bounds return self.spills[key] = {"origin": key, "rows": value.rows, "cols": value.cols, "range": (s, c, c+value.cols-1, r, r+value.rows-1), "children": children[1:]} for child, item in zip(children, value.values): self.values[child] = item fmt = (self.specs.get(child, {}).get("style") or {}).get("format") if child != key else None if fmt or self.formats.get(key): self.formats[child] = fmt or self.formats[key] self.positions.add(child) if child != key: self.spill_parents[child] = key; self.cleared_spills.pop(child, None) # Runtime shape discovery is a dependency event. Newly created targets can have # subscribers that were clean when the input delta was scheduled. queue = [] for child in children[1:]: if child not in self._output_notifications: self._output_notifications.add(child); queue.append(child) seen = set(queue) for child in queue: for owner in self.read_by.get(child, set()) | self.consumed_by.get(child, set()) | self.ranges.at(child, self.stats): if owner in seen: continue # An already evaluated formula needs the newly discovered edge only # if it consumed that address. Static unused branches stay untouched. if owner in self._pass_dirty and (owner in self._pending or owner not in self.consumed_by.get(child, ())): continue seen.add(owner); queue.append(owner) if owner in self.compiled: if owner not in self._pass_dirty: self.stats["visited"] += 1 self._pass_dirty.add(owner); self._pending.add(owner) def _calculate(self, dirty): self._pass_dirty, self._output_notifications = dirty, set() for key in dirty: self._forget_consumed(key) for key in dirty: self._index_array(key) for key in sorted(dirty): self._clear_spill(key) indegree, dependents = {}, {} for key in dirty: self.stats["visited"] += 1 deps = self.reads.get(key, set()) & dirty indegree[key] = len(deps) for ref in deps: dependents.setdefault(ref, []).append(key) self.stats["edges"] += 1 ready = deque(sorted(k for k, degree in indegree.items() if not degree)) ordered = [] while ready: key = ready.popleft() ordered.append(key) for dependent in sorted(dependents.get(key, ())): indegree[dependent] -= 1 if indegree[dependent] == 0: ready.append(dependent) blocked = sorted(dirty - set(ordered)) components = _cyclic_components(set(blocked), self.reads) cyclic = {member for component in components for member in component} self._pass_cyclic = cyclic for component in components: for key in component: self._error(key, "circular_reference") self.provenance[key].update(origin=component[0], via=None, path=component) self.formats.pop(key, None) ordered += [key for key in blocked if key not in cyclic] self._pending = set(ordered) # Dynamic references can discover a dirty target after topological scheduling. # Suspend the current AST, settle its target iteratively, then retry with the same # per-pass volatile values. No recursive dependency walk and no whole-sheet scan. def settle(key): stack, active = [key], {key} while stack: current = stack[-1] if current not in self._pending: stack.pop(); active.discard(current); continue needed = next((ref for ref in self.reads.get(current, ()) if ref in self._pending), None) try: if needed: raise _NeedReference(needed) calculate_one(current) except _NeedReference as exc: ref = str(exc) if ref in active: component = sorted(stack[stack.index(ref):]) for member in component: self._error(member, "circular_reference"); self._pending.discard(member) self.provenance[member].update(origin=component[0], via=None, path=component) cyclic.add(member) else: stack.append(ref); active.add(ref) continue except _ReferenceFault as exc: ref = str(exc); self._error(current, self.errors[ref], ref) self._pending.discard(current) stack.pop(); active.discard(current) def calculate_one(key): self.stats["evaluated"] += 1 self._forget_consumed(key) self.errors.pop(key, None) self.provenance.pop(key, None) inputs = _SheetInputs(self, key) self.formats.pop(key, None) result = evaluate_result(self.compiled[key], inputs, today=self.today) spec = self.specs[key] fmt = (spec.get("style") or {}).get("format") inferred = (spec.get("formulaMeta") or {}).get("inferredFormat") authored = fmt and not (isinstance(inferred, dict) and inferred.get("version") == 1 and inferred.get("format") == fmt) if authored or inputs.last_format: self.formats[key] = fmt if authored else inputs.last_format if result["error"]: self._error(key, result["error"]) else: self._publish(key, result["value"]) for key in sorted(dirty & self.array_roots) + ordered: if key in self._pending: settle(key) while self._pending: settle(min(self._pending)) self.dirty, self.order, self.cyclic = dirty, ordered + sorted(dirty-set(ordered)-cyclic) + sorted(cyclic), sorted(cyclic) def update(self, changes, *, revision, today=None): if revision != self.revision + 1: raise ValueError("a calculation delta requires the next revision; rebuild from the snapshot") self.stats = _calculation_stats() self._volatile_values = {} self._clock = dt.datetime.now(dt.timezone.utc) self.today = today if today is not None else self.today changed = {str(key).upper(): spec for key, spec in changes.items()} self.cleared_spills = {} spill_roots, old_children = set(), set() for key in changed: owner = self.spill_parents.get(key) if owner: spill_roots.add(owner) spill_roots.update(self.prospective.at(key, self.stats)) old_children.update(self.spills.get(key, {}).get("children", ())) for key in changed: self._clear_spill(key) # Disconnect all edited formulas before reconnecting; a multi-cell paste sees one # final graph. Existing range formulas gain/lose formula edges at the changed point. consumers = {key: self.ranges.at(key, self.stats) for key in changed} for key in changed: self._disconnect(key) for key, spec in changed.items(): self._put(key, spec) for key in changed: if key in self.compiled: self._connect(key) for owner in consumers[key] - changed.keys(): if key in self.compiled: self.reads[owner].add(key) self.read_by.setdefault(key, set()).add(owner) elif key not in self.compiled[owner]["cells"]: self.reads[owner].discard(key) self.read_by.get(key, set()).discard(owner) roots = set(changed) | self.volatile_roots | spill_roots | old_children seen, dirty, queue = set(roots), set(), deque(roots) while queue: key = queue.popleft() if key in self.compiled: dirty.add(key) for child in self.spills.get(key, {}).get("children", ()): if child not in seen: seen.add(child); queue.append(child) area = self.prospective_bounds.get(key) if area and (area[2]-area[1]+1)*(area[4]-area[3]+1) <= MAX_RANGE_CELLS: for r in range(area[3], area[4]+1): for c in range(area[1], area[2]+1): child = a1_key(index_to_col(c)+str(r), area[0]) if child not in seen: seen.add(child); queue.append(child) for owner in self.read_by.get(key, set()) | self.consumed_by.get(key, set()) | self.ranges.at(key, self.stats): self.stats["edges"] += 1 if owner not in seen: seen.add(owner) queue.append(owner) self.revision = revision self._calculate(dirty) return self.result() def result(self): return {"values": self.values, "errors": self.errors, "provenance": self.provenance, "formats": self.formats, "spills": self.spills, "spillParents": self.spill_parents, "clearedSpills": self.cleared_spills, "order": self.order, "cyclic": self.cyclic, "dirty": sorted(self.dirty), "revision": self.revision, "stats": dict(self.stats)} def evaluate_sheet(cells, *, today=None, sheets=None): """Compatibility entry point over the same compiled Sheet graph as document refresh. Grid fields retain their separate row evaluator and legacy Boolean DTO. This wrapper preserves its two-key response; document consumers get graph traces and formats directly. """ result = SheetCalculation(cells, today=today, sheets=sheets).result() return {"values": result["values"], "errors": result["errors"]} _DOCUMENT_CACHE_LIMIT = 16 _DOCUMENT_CACHE_CELL_LIMIT = 200_000 _document_calculations = OrderedDict() _document_calculations_lock = RLock() _UNADDRESSABLE_SHEET = "\x00 a tab that cannot be named inside a formula, which is the point \x00" def _document_scopes(tabs): names, seen = [], set() for index, tab in enumerate(tabs): name = str(tab.get("name") or "") if not name or name.upper() in seen: name = _UNADDRESSABLE_SHEET + str(index) names.append(name) seen.add(name.upper()) return names def _document_spec(cell, sheet): # Calculation state/errors on formulas are previous OUTPUT, never trusted input. if cell.get("kind") == "formula" and cell.get("formula"): return {**cell, "formula": cell["formula"], "sheet": sheet} if cell.get("state") == "refused" or cell.get("error"): code = (cell.get("refusal") or cell.get("error") or {}).get("code") or "refused" return {**cell, "refused": code, "sheet": sheet} return {**cell, "sheet": sheet} def _sheet_error_message(code): from modules.sheet import REFUSALS if code in REFUSALS: return REFUSALS[code].format(subject="that database") return { "circular_reference": "This formula refers back to itself, so it has no value.", "bad_formula": "This formula could not be read.", "unknown_ref": "This formula points at a cell that is not filled in.", "unknown_sheet": "This formula points at a tab that is not in this workbook.", "div_zero": "This formula divides by zero.", "no_match": "This lookup found nothing to match.", "bad_value": "This function cannot use one of the values it was given.", "null_intersection": "#NULL! These references do not intersect.", "unknown_name": "#NAME? This name is not defined in this workbook.", "external_reference": "#REF! External workbook references are not supported.", "invalid_reference": "#REF! This reference is outside the worksheet.", "spill_obstructed": "#SPILL! This array needs an empty range inside the worksheet.", "empty_array": "#CALC! This filter has no matching values.", }.get(code, "This formula could not be calculated.") def recompute_document(book, *, cache_key=None, changes=None, today=None): """Recalculate a C7 document in place; return C8 values/errors/provenance/work counters. Only a trusted (tenant, user, workbook) tuple can opt into this process-local bounded LRU. Consecutive revisions plus an explicit accepted delta are required. Unkeyed reads, refreshes, imports, missing revisions, gaps, renames, names and date-system edits rebuild. The output projection visits the cached formula index because the route returns all formula values; it never scans a sheet's cell map on a valid delta. """ with _document_calculations_lock: explicit_today = today is not None calculation_day = str(today or dt.date.today().isoformat())[:10] try: calculation_day = dt.date.fromisoformat(calculation_day).isoformat() except ValueError as exc: raise ValueError("document calculation today must be an ISO date") from exc tabs = [tab for tab in book.get("sheets", ()) if isinstance(tab, dict)] names = _document_scopes(tabs) tab_by_scope = {name.upper(): tab for tab, name in zip(tabs, names)} signature = json.dumps([[(tab.get("id"), name) for tab, name in zip(tabs, names)], book.get("namedRanges"), book.get("dateSystem"), calculation_day], sort_keys=True) revision = book.get("rev") valid_revision = type(revision) is int and revision >= 0 trusted = (isinstance(cache_key, tuple) and len(cache_key) == 3 and all(isinstance(part, str) and part for part in cache_key)) entry = _document_calculations.get(cache_key) if trusted else None incremental = (entry is not None and changes is not None and valid_revision and entry[0] == signature and entry[1].revision + 1 == revision) if incremental: _, engine, formula_keys = entry delta = {} for raw, cell in changes.items(): key = str(raw).upper() scope = _sheet_half(key) if scope not in tab_by_scope: incremental = False break delta[key] = _document_spec(cell, scope) if isinstance(cell, dict) else None if isinstance(cell, dict) and cell.get("kind") == "formula": formula_keys.add(key) else: formula_keys.discard(key) if incremental: engine.update(delta, revision=revision, today=calculation_day if explicit_today else None) if not incremental: specs, formula_keys = {}, set() for tab, name in zip(tabs, names): for addr, cell in (tab.get("cells") or {}).items(): if not isinstance(cell, dict): continue key = a1_key(addr, name) specs[key] = _document_spec(cell, name) if cell.get("kind") == "formula": formula_keys.add(key) engine = SheetCalculation( specs, revision=revision if valid_revision else 0, sheets=names, named_ranges=book.get("namedRanges"), date_system=book.get("dateSystem", "1900"), # A supplied day makes an exceptional repair deterministic. Ordinary workbook # recalculation keeps the live clock, so NOW() does not silently become midnight. today=calculation_day if explicit_today else None) projected = 0 for key in formula_keys: scope, _, addr = key.rpartition("!") cell = (tab_by_scope[scope].get("cells") or {}).get(addr) if not isinstance(cell, dict): continue projected += 1 code = engine.errors.get(key) cell["value"] = engine.values.get(key) if code: message = _sheet_error_message(code) cell.update(state="refused", display="", refusal={"code": code, "message": message}, error={"code": code, "message": message, **engine.provenance.get(key, {})}) excel = {**REFERENCE_ERRORS, "no_match": "#N/A", "bad_value": "#VALUE!", "div_zero": "#DIV/0!", "numeric_error": "#NUM!"}.get(code) if excel: cell["error"]["excelCode"] = excel else: cell.update(state="fresh", display="" if cell["value"] is None else str(cell["value"])) cell.pop("refusal", None) cell.pop("error", None) cell.pop("spill", None) meta = dict(cell.get("formulaMeta") or {}) meta.pop("spill", None) style = dict(cell.get("style") or {}) inherited = meta.pop("inferredFormat", None) if isinstance(inherited, dict) and inherited.get("version") == 1 and inherited.get("format") == style.get("format"): style.pop("format", None) if "format" not in style and engine.formats.get(key) and not code: style["format"] = engine.formats[key] meta["inferredFormat"] = {"version": 1, "format": engine.formats[key]} if style or "style" in cell: cell["style"] = style if key in engine.spills: spill = engine.spills[key] details = {"version": 1, "origin": key, "rows": spill["rows"], "cols": spill["cols"], "ref": addr + ":" + index_to_col(spill["range"][2]) + str(spill["range"][4])} cell["spill"] = details meta["spill"] = details if meta: cell["formulaMeta"] = meta elif "formulaMeta" in cell: cell["formulaMeta"] = {} # These are output records, never authored literals. The formulaMeta marker survives # C7 migration and the existing route's spillParent predicate forwards clears as well. for child, origin in engine.cleared_spills.items(): scope, _, addr = child.rpartition("!") if scope not in tab_by_scope: continue cells = tab_by_scope[scope].setdefault("cells", {}) existing = cells.get(addr) if _occupied(engine.specs.get(child)) or (existing is not None and not _spill_marker(existing, child)): continue base = engine.specs.get(child, {}) cells[addr] = {"kind": "literal", "value": None, "display": "", "state": "typed", **({"style": base["style"]} if base.get("style") else {}), "spillParent": origin, "formulaMeta": {"spillClear": True, "spillChild": {"version": 1, "origin": origin, "address": child, **({"base": base} if base else {})}}} for child, origin in engine.spill_parents.items(): scope, _, addr = child.rpartition("!") owner_scope, _, owner_addr = origin.rpartition("!") owner = tab_by_scope[owner_scope]["cells"][owner_addr] base = engine.specs.get(child, {}) style = {**(owner.get("style") or {}), **(base.get("style") or {})} record = {"kind": "literal", "value": engine.values.get(child), "state": "fresh", "display": "" if engine.values.get(child) is None else str(engine.values[child]), "spillParent": origin, "style": style, "formulaMeta": {"spillChild": {"version": 1, "origin": origin, "address": child, **({"base": base} if base else {})}}} tab_by_scope[scope].setdefault("cells", {})[addr] = record if trusted and valid_revision: _document_calculations[cache_key] = (signature, engine, formula_keys) _document_calculations.move_to_end(cache_key) while (len(_document_calculations) > _DOCUMENT_CACHE_LIMIT or sum(len(item[1].specs) for item in _document_calculations.values()) > _DOCUMENT_CACHE_CELL_LIMIT): _document_calculations.popitem(last=False) elif trusted: _document_calculations.pop(cache_key, None) result = engine.result() result["stats"].update(rebuilt=not incremental, projected=projected) return result def evaluate_batch(definitions, rows, *, consumer, today=None, field_revisions=None): """Evaluate a bounded set of formula definitions over typed consumer rows. Grid, filter, export, automation, Query and Time Series all use this DTO. ``consumer`` is attribution, never an evaluator switch: the result is deliberately identical for every declared surface. """ if consumer not in CONSUMERS: raise FormulaError("formula consumer is not supported") if not isinstance(definitions, dict) or not definitions: raise FormulaError("formula definitions must be a non-empty object") if len(definitions) > MAX_DEFINITIONS: raise FormulaError(f"formula batch has more than {MAX_DEFINITIONS} definitions") clean = {} for key, definition in definitions.items(): if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_]+", key): raise FormulaError("formula definition key is invalid") validate_definition(definition, require_source=True) clean[key] = definition if not isinstance(rows, list) or not rows: raise FormulaError("formula rows must be a non-empty list") if len(rows) > MAX_BATCH_ROWS: raise FormulaError(f"formula batch has more than {MAX_BATCH_ROWS} rows") output, seen_ids = [], set() for item in rows: if not isinstance(item, dict) or not isinstance(item.get("values"), dict): raise FormulaError("each formula row needs an id and values object") row_id = item.get("id") if isinstance(row_id, bool) or not isinstance(row_id, (str, int)) or row_id in seen_ids: raise FormulaError("each formula row id must be a unique string or integer") seen_ids.add(row_id) result = evaluate_fields(clean, item["values"], today=today) output.append({"id": row_id, "values": result["values"], "errors": result["errors"]}) return { "contractVersion": CONTRACT_VERSION, "astVersion": AST_VERSION, "authority": AUTHORITY, "consumer": consumer, "definitions": [ {"key": key, **explain_recalculation(definition, field_revisions or {})} for key, definition in clean.items() ], "rows": output, } def contract_dto(): """Return the complete JSON-safe grammar and executable browser parity corpus.""" inverse_aliases = {} for alias, canonical in ALIASES.items(): inverse_aliases.setdefault(canonical, []).append(alias) functions = [ {"name": name, "minArgs": bounds[0], "maxArgs": bounds[1], "aliases": sorted(inverse_aliases.get(name, []))} for name, bounds in sorted(FN_ARITY.items()) ] operators = [ {"kind": "unary", "canonical": "-", "aliases": []}, *({"kind": "binary", "canonical": token, "aliases": []} for token in ("+", "-", "*", "/", "^", "&")), *({"kind": "comparison", "canonical": token, "aliases": aliases} for token, aliases in (("<", []), ("<=", []), (">", []), (">=", []), ("=", ["=="]), ("!=", ["<>"]))), ] # ⛔⛔ THE ROW COMES FROM `PARITY_ROWS`, AND HARDCODING `{"empty": None}` HERE WAS A PUBLISHED # CONTRACT THAT LIED. W50-T16 gave 20 functions a range argument, and a range reads its values # out of `row` keyed by cell address. With the row hardcoded empty, a consumer running the # PUBLISHED corpus evaluated `SUMIF(B2:B6, ">2", C2:C6)` over no cells and got **0.0** against # a published `expected` of **120.0**. That is the worst shape a fixture can have: not a # refusal a reader can see, but a plausible smaller number that looks like an answer, in a # corpus whose entire job is to let a second implementation prove itself against this one. # MEASURED before the fix: 20 of 101 published function fixtures answered wrongly; after it, 0. fixtures = [ {"id": f"function:{name.lower()}", "kind": "function", "function": name, "source": source, "row": dict(PARITY_ROWS.get(name) or {"empty": None}), "today": "2024-01-02", "expected": expected, "expectedError": None} for name, (source, expected) in PARITY_FIXTURES.items() ] fixtures.extend( {"id": f"operator:{name}", "kind": "operator", "operator": name, "source": source, "row": row, "today": "2024-01-02", "expected": expected, "expectedError": None} for name, (source, row, expected) in OPERATOR_PARITY_FIXTURES.items() ) errors = [ {"id": f"parse:{name}", "phase": "parse", "source": source, "expectedStatus": 400, "expectedError": "bad_formula"} for name, source in PARSE_ERROR_FIXTURES.items() ] errors.extend( {"id": f"evaluate:{name}", "phase": "evaluate", "source": source, "row": row, "today": "2024-01-02", "expected": None, "expectedStatus": 200, "expectedError": expected_error} for name, (source, row, expected_error) in EVALUATION_ERROR_FIXTURES.items() ) errors.extend(( {"id": "definition:source_ast_mismatch", "phase": "definition", "source": "{amount} + 1", "tamperedSource": "{amount} + 2", "row": {"amount": 4}, "expectedStatus": 400, "expectedError": "bad_formula"}, {"id": "batch:cycle", "phase": "batch", "sources": {"a": "{b} + 1", "b": "{a} + 1"}, "rows": [{"id": "2024-01", "values": {}}], "consumer": "timeseries", "expectedStatus": 200, "expectedErrors": {"a": "cycle", "b": "cycle"}}, )) return { "contractVersion": CONTRACT_VERSION, "astVersion": AST_VERSION, "authority": AUTHORITY, "consumers": list(CONSUMERS), "grammar": { "name": "aios-formula", "reference": {"open": "{", "close": "}", "pattern": r"\{[A-Za-z0-9_]+\}", "example": "{amount}", "legacySquareReferenceAccepted": False}, "literals": ["number", "text", "TRUE", "FALSE"], "functionCall": "NAME(argument, ...)", "operators": operators, }, "ast": { "definitionFields": ["version", "source", "ast", "refs"], "nodes": [ {"type": "const", "fields": ["t", "v"]}, {"type": "ref", "fields": ["t", "k"]}, {"type": "neg", "fields": ["t", "e"]}, {"type": "bin", "fields": ["t", "op", "l", "r"]}, {"type": "cmp", "fields": ["t", "op", "l", "r"]}, {"type": "call", "fields": ["t", "fn", "args"]}, ], }, "dto": { "parseRequestRequired": ["source"], "parseResponseRequired": ["contractVersion", "astVersion", "authority", "definition"], "singleEvaluateRequestRequired": ["definition", "row"], "singleEvaluateResponseRequired": ["contractVersion", "astVersion", "authority", "value", "error", "recalculation"], "batchEvaluateRequestRequired": ["consumer", "definitions", "rows"], "batchEvaluateResponseRequired": ["contractVersion", "astVersion", "authority", "consumer", "definitions", "rows"], "batchRequestRowRequired": ["id", "values"], "batchResponseRowRequired": ["id", "values", "errors"], }, "batchFixture": { "id": "timeseries:formula_dependency", "consumer": "timeseries", "sources": {"double": "{amount} * 2", "total": "{double} + 1"}, "rows": [{"id": "2024-01", "values": {"amount": 4}}, {"id": "2024-02", "values": {"amount": 7}}], "expected": [ {"id": "2024-01", "values": {"double": 8.0, "total": 9.0}, "errors": {}}, {"id": "2024-02", "values": {"double": 14.0, "total": 15.0}, "errors": {}}, ], }, "limits": {"sourceCharacters": MAX_SOURCE, "astNodes": MAX_NODES, "astDepth": MAX_DEPTH, "definitionsPerBatch": MAX_DEFINITIONS, "rowsPerBatch": MAX_BATCH_ROWS}, "functions": functions, "errorCodes": ["bad_formula", "unknown_ref", "div_zero", "cycle", "blank", "dependency_error", "evaluation_error"], "fixtures": fixtures, "errors": errors, }