Skip to content

Commit

Permalink
Merge pull request #696 from fkleuver/master
Browse files Browse the repository at this point in the history
fix(parser): left-to-right associativity for nested binary expression…
  • Loading branch information
EisenbergEffect authored Jun 22, 2018
2 parents e7bd80f + ec66237 commit 8cb9597
Show file tree
Hide file tree
Showing 2 changed files with 28 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
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

0 comments on commit 8cb9597

Please sign in to comment.