Skip to content
Open
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
16 changes: 15 additions & 1 deletion src/parser/Parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2560,9 +2560,23 @@ export class Parser {
}

private boolean(): Expression {
let expr = this.booleanAnd();

while (this.match(TokenKind.Or)) {
let operator = this.previous();
this.consumeNewlinesIfAllowed();
let right = this.booleanAnd();
this.addExpressionsToReferences(expr, right);
expr = new BinaryExpression(expr, operator, right);
}

return expr;
}

private booleanAnd(): Expression {
let expr = this.relational();

while (this.matchAny(TokenKind.And, TokenKind.Or)) {
while (this.match(TokenKind.And)) {
let operator = this.previous();
this.consumeNewlinesIfAllowed();
let right = this.relational();
Expand Down
43 changes: 43 additions & 0 deletions src/parser/tests/expression/Boolean.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { Parser } from '../../Parser';
import { TokenKind } from '../../../lexer/TokenKind';
import { EOF, identifier, token } from '../Parser.spec';
import { Range } from 'vscode-languageserver';
import type { AssignmentStatement } from '../../Statement';
import type { BinaryExpression, VariableExpression } from '../../Expression';

describe('parser boolean expressions', () => {

Expand Down Expand Up @@ -87,4 +89,45 @@ describe('parser boolean expressions', () => {
Range.create(0, 4, 0, 18)
);
});

describe('precedence', () => {
function stringify(expr: any): string {
if (expr.operator) {
return `(${stringify(expr.left)} ${expr.operator.text} ${stringify(expr.right)})`;
}
return (expr as VariableExpression).name.text;
}

function parseValue(text: string) {
const { statements, diagnostics } = Parser.parse(text);
expect(diagnostics).to.be.lengthOf(0);
return (statements[0] as AssignmentStatement).value as BinaryExpression;
}

it('binds AND tighter than OR when OR comes first', () => {
const value = parseValue('x = a or b and c');
expect(value.operator.kind).to.equal(TokenKind.Or);
expect(stringify(value)).to.equal('(a or (b and c))');
});

it('binds AND tighter than OR when AND comes first', () => {
const value = parseValue('x = a and b or c');
expect(value.operator.kind).to.equal(TokenKind.Or);
expect(stringify(value)).to.equal('((a and b) or c)');
});

it('binds AND tighter than OR in longer chains', () => {
expect(
stringify(parseValue('x = a or b and c or d and e'))
).to.equal('((a or (b and c)) or (d and e))');
});

it('keeps AND left-associative', () => {
expect(stringify(parseValue('x = a and b and c'))).to.equal('((a and b) and c)');
});

it('keeps OR left-associative', () => {
expect(stringify(parseValue('x = a or b or c'))).to.equal('((a or b) or c)');
});
});
});