Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(parser): left-to-right associativity for nested binary expression… #696

Merged
merged 2 commits into from
Jun 22, 2018
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
2 changes: 1 addition & 1 deletion src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export class ParserImplementation {

while (this.tkn & T$BinaryOp) {
const opToken = this.tkn;
if ((opToken & T$Precedence) < minPrecedence) {
if ((opToken & T$Precedence) <= minPrecedence) {
break;
}
this.nextToken();
Expand Down
27 changes: 27 additions & 0 deletions test/parser.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,33 @@ describe('Parser', () => {
}
});

describe('Binary left-to-right associativity', () => {
const tests = [
{ expr: '4/2*10', expected: 4/2*10 },
{ expr: '4/2*10+1', expected: 4/2*10+1 },
{ expr: '1+4/2+1', expected: 1+4/2+1 },
{ expr: '1+4/2+1+1', expected: 1+4/2+1+1 },
{ expr: '4/2*10', expected: 4/2*10 },
{ expr: '4/2*10/2', expected: 4/2*10/2 },
{ expr: '4/2*10*2', expected: 4/2*10*2 },
{ expr: '4/2*10+2', expected: 4/2*10+2 },
{ expr: '2/4/2*10', expected: 2/4/2*10 },
{ expr: '2*4/2*10', expected: 2*4/2*10 },
{ expr: '2+4/2*10', expected: 2+4/2*10 },
{ expr: '2/4/2*10/2', expected: 2/4/2*10/2 },
{ expr: '2*4/2*10*2', expected: 2*4/2*10*2 },
{ expr: '2+4/2*10+2', expected: 2+4/2*10+2 }
];

for (const { expr, expected } of tests) {
it(`${expr} evaluates to ${expected}`, () => {
const parsed = parser.parse(expr);
const actual = parsed.evaluate({}, {});
expect(actual).toBe(expected);
});
}
});

describe('Binary operator precedence', () => {
const x = [0, 1, 2, 3, 4, 5, 6, 7].map(i => new AccessScope(`x${i}`, 0));
const b = (l, op, r) => new Binary(op, l, r);
Expand Down