Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 43 additions & 20 deletions grammar/parsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,21 @@ interface ParserContext {
getVariable(name: string): any;
}

type OperatorAssociativity = 'left' | 'right';
interface BinaryOperatorGroup {
opSet: ReadonlySet<string>;
associativity: OperatorAssociativity;
}

class Parsing extends EmbeddedActionsParser {
private utils: Utils;
private binaryOperatorsPrecedence: string[][];
private static readonly BINARY_OPERATOR_GROUPS: ReadonlyArray<BinaryOperatorGroup> = [
{ opSet: new Set(['^']), associativity: 'right' },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep exponentiation left-associative for Excel formulas

For Excel-compatible formulas, chained operators at the same precedence are evaluated left-to-right; Microsoft’s Excel precedence docs state this for same-precedence operators, so 2^3^2 should be reduced as (2^3)^2 (64), not 2^(3^2) (512). Marking ^ as right-associative changes results for any chained exponent formula and diverges from Excel behavior.

Useful? React with 👍 / 👎.

{ opSet: new Set(['*', '/']), associativity: 'left' },
{ opSet: new Set(['+', '-']), associativity: 'left' },
{ opSet: new Set(['&']), associativity: 'left' },
{ opSet: new Set(['<', '>', '=', '<>', '<=', '>=']), associativity: 'left' },
];
private c1?: { ALT: () => string }[]; // Cache for alternatives

/**
Expand All @@ -68,13 +80,6 @@ class Parsing extends EmbeddedActionsParser {
// traceInitPerf: true,
});
this.utils = utils;
this.binaryOperatorsPrecedence = [
['^'],
['*', '/'],
['+', '-'],
['&'],
['<', '>', '=', '<>', '<=', '>='],
];
const $ = this;

// Adopted from https://github.com/spreadsheetlab/XLParser/blob/master/src/XLParser/ExcelFormulaGrammar.cs
Expand Down Expand Up @@ -105,17 +110,7 @@ class Parsing extends EmbeddedActionsParser {
values.push($.SUBRULE2(($ as any).formulaWithPercentOp));
});
$.ACTION(() => {
// evaluate
for (const ops of this.binaryOperatorsPrecedence) {
for (let index = 0, length = infixes.length; index < length; index++) {
const infix = infixes[index];
if (!ops.includes(infix)) continue;
infixes.splice(index, 1);
values.splice(index, 2, this.utils.applyInfix(values[index], infix, values[index + 1]));
index--;
length--;
}
}
this.reduceBinaryOperators(values, infixes);
});

return values[0];
Expand All @@ -128,7 +123,7 @@ class Parsing extends EmbeddedActionsParser {

($ as any).RULE('formulaWithPercentOp', () => {
let value = $.SUBRULE(($ as any).formulaWithUnaryOp);
$.OPTION(() => {
$.MANY(() => {
const postfix = $.CONSUME(PercentOp).image;
value = $.ACTION(() => this.utils.applyPostfix(value, postfix));
});
Expand Down Expand Up @@ -399,6 +394,34 @@ class Parsing extends EmbeddedActionsParser {

this.performSelfAnalysis();
}

private reduceBinaryOperators(values: any[], infixes: string[]): void {
for (const { opSet, associativity } of Parsing.BINARY_OPERATOR_GROUPS) {
if (associativity === 'right') {
// Right-associative groups, currently exponentiation, must reduce from the end.
for (let index = infixes.length - 1; index >= 0; index--) {
if (!opSet.has(infixes[index])) continue;
this.applyInfixAt(values, infixes, index);
}
continue;
}

for (let index = 0, length = infixes.length; index < length; index++) {
if (!opSet.has(infixes[index])) continue;
this.applyInfixAt(values, infixes, index);
// Re-check the same position because splicing shifts later operators left.
index--;
length--;
}
}
}

private applyInfixAt(values: any[], infixes: string[], index: number): void {
const infix = infixes[index];
infixes.splice(index, 1);
values.splice(index, 2, this.utils.applyInfix(values[index], infix, values[index + 1]));
}

}

export {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"jstat": "^1.9.6"
},
"devDependencies": {
"@types/node": "24.1.0",
"@vitest/coverage-v8": "^2.1.1",
"coveralls-next": "^5.0.0",
"docdash": "^2.0.2",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 25 additions & 1 deletion test/operators/testcase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,34 @@ const testCases: TestCase = {
'A13+1': 1
},
'Operator Precedence': {
// '1+2*2': 5,
'1+2*2': 5,
'1+4/2+1': 4,
'1+4/2+2*3': 9,
'(1+4/2+2*3)/3^2': 1,
'2^3^2': 512,
'2^3^2^1': 512,
'2*3^2^2': 162,
'2^3*2': 16,
'(2^3)^2': 64,
'-2^2': 4,
'-(2^2)': -4,
'8/4/2': 1,
'10-3-2': 5,
'"a"&"b"&"c"': 'abc',
'"x"&1+2': 'x3',
'1+2&"x"': '3x',
'1+2=3': true,
'"a"&"b"="ab"': true,
// Chained comparisons are reduced left-to-right, not treated as mathematical ranges.
'1<2<3': false,
'3>2>1': true,
'200%^2': 4,
'200%%^2': 0.0004,
'100%%': 0.01,
'100% %': 0.01,
'5%%%': 0.000005,
'1%%%%': 0.00000001,
'(200+300)%%': 0.05,
'1-234/78+9/-78+45%': -1.6653846153846200
},
'Intersection Test': {
Expand Down
Loading