/** * Formula parser: tokenizer + Pratt parser producing the AST in `types.ts`. * * Pure and dependency-free — usable standalone for linting/ref-extraction. * The precedence table encodes Excel's quirks precisely (see the binding-power * constants), because those are exactly what golden-file tests catch: * - unary minus binds TIGHTER than `^` (`-2^2` = 4, not -4) * - `^` is LEFT-associative (`2^3^2` = 64, not 512) * - `%` is a postfix operator, tighter than `^` * - `&` sits between arithmetic and comparison */ import { MAX_COLS, MAX_ROWS, letterToCol, parseA1 } from './addr' import type { ErrorCode, NameNode, Node, RangeNode, RefNode, SheetId, UnaryOperator, } from './types' // --------------------------------------------------------------------------- // Errors // --------------------------------------------------------------------------- export class ParseError extends Error { readonly pos: number constructor(message: string, pos: number) { super(`${message} (at ${pos})`) this.name = 'ParseError' this.pos = pos } } /** Options reserved for future locale support (arg separator, decimal mark). */ export interface ParseOptions { /** Sheet a bare (unqualified) reference resolves against. Optional. */ defaultSheet?: SheetId } // --------------------------------------------------------------------------- // Tokenizer // --------------------------------------------------------------------------- type TokType = | 'num' | 'str' | 'err' | 'ref' | 'name' | 'sheet' | 'op' | 'lparen' | 'rparen' | 'comma' | 'colon' | 'bang' | 'eof' interface Token { type: TokType value: string pos: number } const ERROR_CODES: Array = [ '#REF!', '#DIV/0!', '#NAME?', '#VALUE!', '#N/A', '#NUM!', '#NULL!', ] // Sticky regexes (matched at the current position). const RE = { ws: /\s+/y, // number: 123, 1.5, .5, 1e10, 2.5E-3 num: /(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y, str: /"(?:[^"]|"")*"/y, sheetQuoted: /'(?:[^']|'')*'/y, // a cell ref: optional $, 1-3 letters, optional $, digits cellRef: /\$?[A-Za-z]{1,3}\$?\d+/y, // a name/identifier (function, defined name, bare column letters, TRUE/FALSE) name: /\$?[A-Za-z_][A-Za-z0-9_.]*/y, } as const function isIdentChar(ch: string): boolean { return /[A-Za-z0-9_.]/.test(ch) } export function tokenize(src: string): Array { const tokens: Array = [] let pos = 0 const n = src.length const stick = (re: RegExp): string | null => { re.lastIndex = pos const m = re.exec(src) return m ? m[0] : null } while (pos < n) { const ch = src[pos]! // whitespace (note: Excel's space-intersection operator is intentionally // not supported yet — whitespace is simply skipped) if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { const ws = stick(RE.ws)! pos += ws.length continue } // string literal if (ch === '"') { const s = stick(RE.str) if (!s) throw new ParseError('unterminated string', pos) tokens.push({ type: 'str', value: s, pos }) pos += s.length continue } // single-quoted sheet name if (ch === "'") { const s = stick(RE.sheetQuoted) if (!s) throw new ParseError('unterminated sheet name', pos) tokens.push({ type: 'sheet', value: s.slice(1, -1).replace(/''/g, "'"), pos, }) pos += s.length continue } // error literal (must be matched before the '/' division operator) if (ch === '#') { const code = ERROR_CODES.find((c) => src.startsWith(c, pos)) if (!code) throw new ParseError('unknown error literal', pos) tokens.push({ type: 'err', value: code, pos }) pos += code.length continue } // number if (ch >= '0' && ch <= '9') { const num = stick(RE.num)! tokens.push({ type: 'num', value: num, pos }) pos += num.length continue } if ( ch === '.' && pos + 1 < n && src[pos + 1]! >= '0' && src[pos + 1]! <= '9' ) { const num = stick(RE.num)! tokens.push({ type: 'num', value: num, pos }) pos += num.length continue } // multi-char operators const two = src.slice(pos, pos + 2) if (two === '<=' || two === '>=' || two === '<>') { tokens.push({ type: 'op', value: two, pos }) pos += 2 continue } // single-char punctuation & operators switch (ch) { case '(': tokens.push({ type: 'lparen', value: ch, pos }) pos++ continue case ')': tokens.push({ type: 'rparen', value: ch, pos }) pos++ continue case ',': tokens.push({ type: 'comma', value: ch, pos }) pos++ continue case ':': tokens.push({ type: 'colon', value: ch, pos }) pos++ continue case '!': tokens.push({ type: 'bang', value: ch, pos }) pos++ continue case '+': case '-': case '*': case '/': case '^': case '&': case '=': case '<': case '>': case '%': tokens.push({ type: 'op', value: ch, pos }) pos++ continue } // cell ref vs name — try the ref pattern, but reclassify as a name if it is // actually part of a longer identifier (e.g. `A1B2`), a function call // (e.g. `LOG10(`), or a sheet qualifier (e.g. `S1!A1`, where `S1` is a sheet // name that happens to look like a cell reference). const refMatch = stick(RE.cellRef) if (refMatch) { const after = src[pos + refMatch.length] const isName = after !== undefined && (after === '(' || after === '!' || isIdentChar(after)) if (!isName) { tokens.push({ type: 'ref', value: refMatch, pos }) pos += refMatch.length continue } } const nameMatch = stick(RE.name) if (nameMatch) { tokens.push({ type: 'name', value: nameMatch, pos }) pos += nameMatch.length continue } throw new ParseError(`unexpected character '${ch}'`, pos) } tokens.push({ type: 'eof', value: '', pos }) return tokens } // --------------------------------------------------------------------------- // Parser (Pratt) // --------------------------------------------------------------------------- // Binding powers. Higher binds tighter. The ordering IS the Excel precedence // table; do not reorder without a golden-file reason. const BP_COMPARISON = 10 // = <> < <= > >= const BP_CONCAT = 20 // & const BP_ADD = 30 // binary + - const BP_MUL = 40 // * / const BP_POW = 50 // ^ (left-assoc) const BP_PERCENT = 60 // % postfix const BP_UNARY = 65 // prefix - + (tighter than ^ and %) const BP_RANGE = 80 // : (tightest) // A transient node used only during parsing for bare identifiers that might be // a whole-column reference (`A` in `A:A`) or a boolean/defined name. interface NameToken { type: 'nametoken' name: string /** Sheet qualifier when written `Sheet1!MyName`. */ sheet?: SheetId pos: number } type PNode = Node | NameToken class Parser { private readonly toks: Array private i = 0 private readonly defaultSheet?: SheetId constructor(toks: Array, opts?: ParseOptions) { this.toks = toks this.defaultSheet = opts?.defaultSheet } private peek(): Token { return this.toks[this.i]! } private next(): Token { return this.toks[this.i++]! } private expect(type: TokType): Token { const t = this.peek() if (t.type !== type) { throw new ParseError( `expected ${type} but found '${t.value || t.type}'`, t.pos, ) } return this.next() } parse(): Node { const node = this.resolve(this.expr(0)) if (this.peek().type !== 'eof') { throw new ParseError(`unexpected '${this.peek().value}'`, this.peek().pos) } return node } // Pratt loop. private expr(minBp: number): PNode { let left = this.nud() for (;;) { const t = this.peek() if (t.type === 'colon') { if (BP_RANGE < minBp) break this.next() const right = this.expr(BP_RANGE + 1) // left-assoc: exclude same-bp on the right left = this.makeRange(left, right, t.pos) continue } if (t.type === 'op') { // postfix percent if (t.value === '%') { if (BP_PERCENT < minBp) break this.next() left = { type: 'unary', op: '%', operand: this.resolve(left) } continue } const bp = this.binBp(t.value) if (bp === null || bp < minBp) break this.next() // All binary operators are left-associative — including `^`, which is // the Excel quirk (`2^3^2` = 64). Left-assoc means the right operand is // parsed at `bp + 1`, so a following same-precedence op is NOT folded in. const right = this.expr(bp + 1) left = { type: 'binary', op: t.value as never, left: this.resolve(left), right: this.resolve(right), } continue } break } return left } private binBp(op: string): number | null { switch (op) { case '=': case '<>': case '<': case '<=': case '>': case '>=': return BP_COMPARISON case '&': return BP_CONCAT case '+': case '-': return BP_ADD case '*': case '/': return BP_MUL case '^': return BP_POW default: return null } } // Null denotation: literals, prefixes, groups, references, calls. private nud(): PNode { const t = this.next() switch (t.type) { case 'num': return { type: 'number', value: Number(t.value) } case 'str': return { type: 'string', value: t.value.slice(1, -1).replace(/""/g, '"'), } case 'err': return { type: 'error', code: t.value as ErrorCode } case 'ref': return this.refFrom(t.value, t.pos) case 'sheet': return this.qualified(t.value, t.pos) case 'name': return this.nameNud(t) case 'op': if (t.value === '-' || t.value === '+') { const operand = this.resolve(this.expr(BP_UNARY)) return { type: 'unary', op: t.value as UnaryOperator, operand } } throw new ParseError(`unexpected operator '${t.value}'`, t.pos) case 'lparen': { const inner = this.resolve(this.expr(0)) this.expect('rparen') return inner } default: throw new ParseError(`unexpected '${t.value || t.type}'`, t.pos) } } private nameNud(t: Token): PNode { // function call? if (this.peek().type === 'lparen') { return this.call(t.value) } // sheet qualifier: `Sheet2!...` if (this.peek().type === 'bang') { this.next() // consume '!' return this.qualified(t.value, t.pos) } const upper = t.value.toUpperCase() if (upper === 'TRUE') return { type: 'bool', value: true } if (upper === 'FALSE') return { type: 'bool', value: false } // Otherwise a bare name: keep it transient — it may be a whole-column ref // endpoint (`A` in `A:A`); if it survives to `resolve` it's an unsupported // defined name. return { type: 'nametoken', name: t.value, pos: t.pos } } private call(name: string): Node { this.expect('lparen') const args: Array = [] if (this.peek().type !== 'rparen') { args.push(this.resolve(this.expr(0))) while (this.peek().type === 'comma') { this.next() args.push(this.resolve(this.expr(0))) } } this.expect('rparen') return { type: 'call', name: name.toUpperCase(), args } } // A sheet-qualified primary. The '!' has already been consumed for the bare // name case; for the quoted case we consume it here. private qualified(sheet: SheetId, pos: number): PNode { if (this.toks[this.i - 1]!.type === 'sheet') { this.expect('bang') } const t = this.next() if (t.type === 'ref') { const r = this.refFrom(t.value, t.pos) r.sheet = sheet return r } if (t.type === 'name') { // Either a whole-column cross-sheet ref (`Sheet1!A:A`, resolved when // combined with ':') or a sheet-scoped defined name (`Sheet1!MyName`). return { type: 'nametoken', name: t.value, sheet, pos: t.pos } } throw new ParseError(`expected a reference after '${sheet}!'`, pos) } private refFrom(text: string, pos: number): RefNode { const parsed = parseA1(text) if (!parsed) throw new ParseError(`invalid reference '${text}'`, pos) // `sheet` is left undefined here — a bare ref is only *explicitly* qualified // through `qualified()`. The default sheet is applied late (in `resolve` for // a standalone ref, in `makeRange` for a range endpoint), so a range endpoint // can tell "no sheet written" from "the default sheet" and inherit the other // endpoint's sheet correctly (`txn!B2:B4` is single-sheet, not 3D). return { type: 'ref', col: parsed.col, row: parsed.row, colAbs: parsed.colAbs, rowAbs: parsed.rowAbs, } } // Build a RangeNode from two endpoints. Supports cell:cell, col:col (`A:A`), // and row:row (`1:1`). The sheet on the start endpoint distributes to the end. private makeRange(leftP: PNode, rightP: PNode, pos: number): RangeNode { const start = this.endpoint(leftP, pos) const end = this.endpoint(rightP, pos) if (start.kind !== end.kind) { throw new ParseError('mismatched range endpoints', pos) } let s: RefNode let e: RefNode if (start.kind === 'cell') { s = start.ref e = (end as CellEndpoint).ref } else if (start.kind === 'col') { s = { type: 'ref', col: start.col, row: 0, colAbs: start.abs, rowAbs: false, } e = { type: 'ref', col: (end as ColEndpoint).col, row: MAX_ROWS - 1, colAbs: (end as ColEndpoint).abs, rowAbs: false, } } else { s = { type: 'ref', col: 0, row: start.row, colAbs: false, rowAbs: start.abs, } e = { type: 'ref', col: MAX_COLS - 1, row: (end as RowEndpoint).row, colAbs: false, rowAbs: (end as RowEndpoint).abs, } } // Each endpoint keeps its own sheet. A missing sheet inherits the other // endpoint's (so `Sheet2!A1:B2` qualifies both); when both endpoints name a // sheet and they differ, this is a 3D range and the two are preserved. const origS = s.sheet const origE = e.sheet s.sheet = origS ?? origE ?? this.defaultSheet e.sheet = origE ?? origS ?? this.defaultSheet return { type: 'range', start: s, end: e } } private endpoint(node: PNode, pos: number): Endpoint { if (node.type === 'ref') return { kind: 'cell', ref: node } if (node.type === 'number') { const row = node.value if (!Number.isInteger(row) || row < 1 || row > MAX_ROWS) { throw new ParseError('invalid row in range', pos) } return { kind: 'row', row: row - 1, abs: false } } if (node.type === 'nametoken') { const m = /^(\$?)([A-Za-z]{1,3})$/.exec(node.name) if (m) { const col = letterToCol(m[2]!) if (col < MAX_COLS) return { kind: 'col', col, abs: m[1] === '$' } } throw new ParseError(`invalid range endpoint '${node.name}'`, pos) } throw new ParseError('invalid range endpoint', pos) } // Collapse a transient name node into a final AST node. A bare identifier // that survived (not a function, boolean, or column/row endpoint) becomes a // defined-name reference, resolved against the workbook name table at // evaluation time (an undefined name evaluates to `#NAME?`). private resolve(node: PNode): Node { if (node.type === 'nametoken') { return node.sheet === undefined ? { type: 'name', name: node.name } : { type: 'name', name: node.name, sheet: node.sheet } } // A standalone reference with no explicit qualifier resolves against the // default sheet (range endpoints are finalized in `makeRange` instead). if (node.type === 'ref' && node.sheet === undefined) { return { ...node, sheet: this.defaultSheet } } return node } } interface CellEndpoint { kind: 'cell' ref: RefNode } interface ColEndpoint { kind: 'col' col: number abs: boolean } interface RowEndpoint { kind: 'row' row: number abs: boolean } type Endpoint = CellEndpoint | ColEndpoint | RowEndpoint /** Parse a formula string (with or without a leading `=`) into an AST. */ export function parse(input: string, opts?: ParseOptions): Node { const body = input[0] === '=' ? input.slice(1) : input const parser = new Parser(tokenize(body), opts) return parser.parse() } // --------------------------------------------------------------------------- // Reference extraction (the DepParser primitive M3 builds the graph from) // --------------------------------------------------------------------------- export type FormulaRef = | { kind: 'cell'; ref: RefNode } | { kind: 'range'; range: RangeNode } | { kind: 'name'; name: NameNode } /** * Collect every reference/range/name a formula reads, for dependency tracking. * A defined name is reported as a `name` ref; the dependency analyzer resolves * it against the workbook name table and flows precedents through it, so a * formula recalcs when its named target changes. */ export function refsOf(node: Node): Array { const out: Array = [] const walk = (n: Node): void => { switch (n.type) { case 'ref': out.push({ kind: 'cell', ref: n }) break case 'range': out.push({ kind: 'range', range: n }) break case 'name': out.push({ kind: 'name', name: n }) break case 'unary': walk(n.operand) break case 'binary': walk(n.left) walk(n.right) break case 'call': for (const a of n.args) walk(a) break default: break } } walk(node) return out }