Skip to content

Commit

Permalink
fix(parser): left-to-right associativity for nested binary expression…
Browse files Browse the repository at this point in the history
…s with same precedence
  • Loading branch information
fkleuver committed Jun 21, 2018
1 parent e7bd80f commit d2d867e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
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
14 changes: 14 additions & 0 deletions test/parser.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,20 @@ describe('Parser', () => {
}
});

describe('Binary left-to-right associativity', () => {
it('4/2*10', () => {
const expr = parser.parse('4/2*10');
const res = expr.evaluate({}, {});
expect(res).toBe(20);
});

it('4-2+10', () => {
const expr = parser.parse('4-2+10');
const res = expr.evaluate({}, {});
expect(res).toBe(12);
});
});

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

0 comments on commit d2d867e

Please sign in to comment.