/** * Evaluator: walk an AST against a resolver + function registry, producing a * CellValue. Errors are values and propagate through every operator. */ import { makeRect } from './addr' import type { AsyncArgValue, AsyncRequest, Clock, FnArgs, FunctionPorts, FunctionRegistry, RangeArg, Rng, VisibilityPort, } from './ports' import type { Sheet } from './sheet' import type { BlockingValue, CellValue, ErrorCode, ErrorValue, NameNode, Node, PendingValue, RangeNode, Ref, RefNode, SheetId, } from './types' /** * The evaluator's view of the async scheduler (§3). The evaluator stays * synchronous: on reaching an async call it looks up a cached result or records * a request and returns `pending`. It never awaits. */ export interface AsyncEvalHook { /** Resolved/cached value for a call key, or `undefined` if not yet available. */ lookup: (key: string) => CellValue | undefined /** Register a cache-miss request produced during this recalc pass. */ collect: (req: AsyncRequest, cell?: Ref) => void } /** What the evaluator needs from the workbook — kept narrow for testability. */ export interface Environment { getCellValue: (sheet: SheetId, row: number, col: number) => CellValue getSheet: (sheet: SheetId) => Sheet | undefined functions: FunctionRegistry clock: Clock rng: Rng visibility?: VisibilityPort /** Host-provided ports surfaced to every function via `FnContext.ports`. */ ports?: FunctionPorts /** Async scheduler hook; absent for purely synchronous workbooks. */ async?: AsyncEvalHook /** * Resolve a defined name to its definition AST, given the sheet of the * formula that references it (for sheet-scope fallback). `undefined` when the * name is not defined (the evaluator then yields `#NAME?`). Absent entirely on * environments with no name table. */ resolveName?: ( name: string, ownerSheet: SheetId | undefined, scope?: SheetId, ) => Node | undefined /** * The workbook's sheets in order — load-bearing for 3D ranges, whose span is * the slice between the two endpoint sheets. Absent environments treat every * range as single-sheet. */ sheetOrder?: () => Array } /** * The call key for an async request: `name + version + argument values` (§3.1). * Stable and deterministic so the whole workbook dedupes on it and a saved * result rehydrates to the same key. Blocking args never reach here (the * evaluator propagates them first), so a plain JSON encoding is sufficient. */ /** * Field separator inside a call key (the name, version, and JSON-encoded args). A NUL, so it can't * occur in a function name or JSON — the scheduler splits/prefixes on it for * per-function invalidation. */ export const CALL_KEY_SEP = '\u0000' export function callKey( name: string, version: string, args: Array, ): string { return ( name.toUpperCase() + CALL_KEY_SEP + version + CALL_KEY_SEP + JSON.stringify(args) ) } export function err(code: ErrorCode, detail?: string): ErrorValue { return detail === undefined ? { kind: 'error', code } : { kind: 'error', code, detail } } export function isErr(v: CellValue): v is ErrorValue { return v !== null && typeof v === 'object' && v.kind === 'error' } /** The single shared `pending` marker (identity is irrelevant — it is a tag). */ const PENDING: PendingValue = { kind: 'pending' } export function pending(): PendingValue { return PENDING } export function isPending(v: CellValue): v is PendingValue { return v !== null && typeof v === 'object' && v.kind === 'pending' } /** * True for values that short-circuit evaluation — errors *and* not-yet-arrived * (`pending`) results. Both propagate the same way through operators and * coercions; functions that must distinguish them (e.g. `IFERROR`, `IFPENDING`) * check {@link isErr}/{@link isPending} explicitly instead. */ export function isBlocking(v: CellValue): v is BlockingValue { return ( v !== null && typeof v === 'object' && (v.kind === 'error' || v.kind === 'pending') ) } // --------------------------------------------------------------------------- // Coercions // --------------------------------------------------------------------------- /** Coerce to a number for arithmetic. Errors and `pending` propagate unchanged. */ export function toNum(v: CellValue): number | BlockingValue { if (isBlocking(v)) return v if (typeof v === 'number') return v if (typeof v === 'boolean') return v ? 1 : 0 if (v === null) return 0 const n = Number(v) if (v.trim() !== '' && !Number.isNaN(n) && Number.isFinite(n)) return n return err('#VALUE!') } /** Coerce to a display string. Errors and `pending` propagate unchanged. */ export function toStr(v: CellValue): string | BlockingValue { if (isBlocking(v)) return v if (v === null) return '' if (typeof v === 'boolean') return v ? 'TRUE' : 'FALSE' if (typeof v === 'number') return String(v) return v } /** Coerce to boolean for logical contexts. Blank/"" is false. */ export function toBool(v: CellValue): boolean | BlockingValue { if (isBlocking(v)) return v if (typeof v === 'boolean') return v if (typeof v === 'number') return v !== 0 if (v === null) return false const u = v.toUpperCase() if (u === 'TRUE') return true if (u === 'FALSE' || u === '') return false return err('#VALUE!') } /** Numeric view for comparison, or null if the value is non-numeric text. */ function compNum(v: CellValue): number | null { if (isBlocking(v)) return null if (typeof v === 'number') return v if (typeof v === 'boolean') return v ? 1 : 0 if (v === null) return 0 const n = Number(v) return v.trim() !== '' && !Number.isNaN(n) ? n : null } /** Excel-ish loose ordering: numeric when both sides read as numbers, else text. */ export function looseCompare(a: CellValue, b: CellValue): number { const na = compNum(a) const nb = compNum(b) if (na !== null && nb !== null) return na < nb ? -1 : na > nb ? 1 : 0 const sa = String(a ?? '').toUpperCase() const sb = String(b ?? '').toUpperCase() return sa < sb ? -1 : sa > sb ? 1 : 0 } // --------------------------------------------------------------------------- // Range materialization // --------------------------------------------------------------------------- function rangeArgFromRect( env: Environment, sheet: SheetId, r0: number, c0: number, r1: number, c1: number, ): RangeArg { const rect = makeRect(r0, c0, r1, c1) return { sheet, r0: rect.r0, c0: rect.c0, rows: rect.r1 - rect.r0 + 1, cols: rect.c1 - rect.c0 + 1, *cells() { const s = env.getSheet(sheet) if (!s) return for (const hit of s.iterateRect(rect)) { yield { r: hit.row - rect.r0, c: hit.col - rect.c0, value: hit.cell.value, } } }, at(r, c) { return env.getCellValue(sheet, rect.r0 + r, rect.c0 + c) }, } } /** * A 3D range spanning `span` sheets: the same rectangle on each sheet, stacked * row-wise so sheet `k` occupies rows `[k*rectRows, (k+1)*rectRows)`. Aggregates * (SUM/COUNT/…) read `cells()` across the stack; `at()` maps a flat row back to * its sheet. Sheets in the span with no backing `Sheet` contribute nothing. */ function multiSheetRangeArg( env: Environment, span: Array, start: RefNode, end: RefNode, ): RangeArg { const rect = makeRect(start.row, start.col, end.row, end.col) const rectRows = rect.r1 - rect.r0 + 1 const rectCols = rect.c1 - rect.c0 + 1 return { sheet: span[0]!, r0: rect.r0, c0: rect.c0, rows: span.length * rectRows, cols: rectCols, *cells() { for (let k = 0; k < span.length; k++) { const s = env.getSheet(span[k]!) if (!s) continue const base = k * rectRows for (const hit of s.iterateRect(rect)) { yield { r: base + (hit.row - rect.r0), c: hit.col - rect.c0, value: hit.cell.value, } } } }, at(r, c) { const k = Math.floor(r / rectRows) const sheet = span[k] if (sheet === undefined) return null return env.getCellValue(sheet, rect.r0 + (r % rectRows), rect.c0 + c) }, } } function rangeFromRangeNode( node: RangeNode, env: Environment, ): RangeArg | null { const s0 = node.start.sheet const s1 = node.end.sheet if (s0 === undefined || s1 === undefined) return null if (s0 === s1) { return rangeArgFromRect( env, s0, node.start.row, node.start.col, node.end.row, node.end.col, ) } // 3D range: iterate the block on every sheet in the span, in workbook order. const order = env.sheetOrder ? env.sheetOrder() : [] const i0 = order.indexOf(s0) const i1 = order.indexOf(s1) if (i0 < 0 || i1 < 0) return null const span = order.slice(Math.min(i0, i1), Math.max(i0, i1) + 1) return multiSheetRangeArg(env, span, node.start, node.end) } /** Resolve a defined-name node against the environment's name table. */ function resolveNameNode( node: NameNode, env: Environment, cell?: Ref, ): Node | undefined { return env.resolveName?.(node.name, cell?.sheet, node.sheet) } /** * Materialize a {@link RangeArg} to a dense 2D grid for an async argument, * propagating any blocking cell. Bounded: a range larger than 65 536 cells is * rejected (`#VALUE!`) rather than materialized — async range arguments are * label lists, not whole columns. */ function materializeGrid( rng: RangeArg, ): Array> | BlockingValue { if (rng.rows * rng.cols > 65_536) return err('#VALUE!') const grid: Array> = [] for (let r = 0; r < rng.rows; r++) { const row: Array = [] for (let c = 0; c < rng.cols; c++) { const v = rng.at(r, c) if (isBlocking(v)) return v row.push(v) } grid.push(row) } return grid } /** True when a node denotes a multi-cell range — a `range`, or a name bound to one. */ function isRangeShaped(node: Node, env: Environment, cell?: Ref): boolean { if (node.type === 'range') return true if (node.type === 'name') { const def = env.resolveName?.(node.name, cell?.sheet, node.sheet) return def?.type === 'range' } return false } function rangeArgOf(node: Node, env: Environment, cell?: Ref): RangeArg | null { if (node.type === 'range') return rangeFromRangeNode(node, env) if (node.type === 'ref') { const r = node if (r.sheet === undefined) return null return rangeArgFromRect(env, r.sheet, r.row, r.col, r.row, r.col) } if (node.type === 'name') { const def = resolveNameNode(node, env, cell) // A name that binds to a range/ref materializes like one written inline. if (def && (def.type === 'range' || def.type === 'ref')) { return rangeArgOf(def, env, cell) } return null } return null } // --------------------------------------------------------------------------- // Evaluation // --------------------------------------------------------------------------- /** * Evaluate an AST to a scalar `CellValue`. `cell`, when supplied, is the cell * that owns the formula; it flows unchanged into each `FnContext.cell` so * functions can know their location (ad-hoc `runFormula` passes none). */ export function evaluate(ast: Node, env: Environment, cell?: Ref): CellValue { return evalScalar(ast, env, cell) } function evalScalar(node: Node, env: Environment, cell?: Ref): CellValue { switch (node.type) { case 'number': return node.value case 'string': return node.value case 'bool': return node.value case 'error': return err(node.code) case 'ref': { if (node.sheet === undefined) return err('#REF!') return env.getCellValue(node.sheet, node.row, node.col) } case 'range': // A range used where a single value is expected. return err('#VALUE!') case 'name': { const def = resolveNameNode(node, env, cell) if (!def) return err('#NAME?') // A name bound to a range used in scalar context is a #VALUE! like a bare // range; otherwise evaluate its definition in place. return evalScalar(def, env, cell) } case 'unary': return evalUnary(node, env, cell) case 'binary': return evalBinary(node, env, cell) case 'call': return evalCall(node, env, cell) } } function evalUnary( node: Extract, env: Environment, cell?: Ref, ): CellValue { const v = toNum(evalScalar(node.operand, env, cell)) if (isBlocking(v)) return v switch (node.op) { case '-': return -v case '+': return v case '%': return v / 100 } } function evalBinary( node: Extract, env: Environment, cell?: Ref, ): CellValue { const op = node.op if (op === '&') { const a = toStr(evalScalar(node.left, env, cell)) if (isBlocking(a)) return a const b = toStr(evalScalar(node.right, env, cell)) if (isBlocking(b)) return b return a + b } if ( op === '=' || op === '<>' || op === '<' || op === '<=' || op === '>' || op === '>=' ) { const a = evalScalar(node.left, env, cell) if (isBlocking(a)) return a const b = evalScalar(node.right, env, cell) if (isBlocking(b)) return b const c = looseCompare(a, b) switch (op) { case '=': return c === 0 case '<>': return c !== 0 case '<': return c < 0 case '<=': return c <= 0 case '>': return c > 0 case '>=': return c >= 0 } } // arithmetic const a = toNum(evalScalar(node.left, env, cell)) if (isBlocking(a)) return a const b = toNum(evalScalar(node.right, env, cell)) if (isBlocking(b)) return b switch (op) { case '+': return a + b case '-': return a - b case '*': return a * b case '/': return b === 0 ? err('#DIV/0!') : a / b case '^': { const r = Math.pow(a, b) return Number.isFinite(r) ? r : err('#NUM!') } } } function evalCall( node: Extract, env: Environment, cell?: Ref, ): CellValue { const def = env.functions.get(node.name) if (!def) return err('#NAME?') const min = def.minArgs ?? 0 const max = def.maxArgs ?? min if (node.args.length < min || node.args.length > max) return err('#VALUE!') // --- async functions: look up the cache or record a request, return pending -- if (def.kind === 'async') { if (!env.async) return pending() // no scheduler wired: result can't arrive const argv: Array = [] for (let i = 0; i < node.args.length; i++) { // A genuine range argument (a `A1:B2` range, or a name resolving to one) // is materialized to a 2D grid and folded into the call key by content — a // non-builtin async function gets ranges like a builtin. A single-cell ref // stays a scalar (so `JEV.CHOICE(A2, "csv")` is unaffected). const argNode = node.args[i]! if (isRangeShaped(argNode, env, cell)) { const rng = rangeArgOf(argNode, env, cell) const grid = rng ? materializeGrid(rng) : err('#REF!') // A 2D array is the materialized grid; anything else is a blocking value. if (!Array.isArray(grid)) return grid argv.push(grid) continue } const v = evalScalar(argNode, env, cell) // A blocking (pending/error) argument means we can't form a stable call // key yet — propagate it rather than firing a request against a stale key. if (isBlocking(v)) return v argv.push(v) } const version = def.version ?? '0' const key = callKey(node.name, version, argv) const cached = env.async.lookup(key) if (cached !== undefined) return cached env.async.collect( { name: node.name.toUpperCase(), version, args: argv, key }, cell, ) return pending() } if (!def.evaluate) return err('#VALUE!') // misconfigured async-less descriptor const scalarCache = new Map() const args: FnArgs = { length: node.args.length, scalar(i) { if (scalarCache.has(i)) return scalarCache.get(i)! const v = evalScalar(node.args[i]!, env, cell) scalarCache.set(i, v) return v }, range(i) { return rangeArgOf(node.args[i]!, env, cell) }, node(i) { return node.args[i]! }, } return def.evaluate({ args, clock: env.clock, rng: env.rng, visibility: env.visibility, ports: env.ports, cell, }) }