From ab0deae0ef94a7ae7787cd836f66d593694fe92f Mon Sep 17 00:00:00 2001 From: Chen Dai Date: Wed, 14 Dec 2022 09:26:51 -0800 Subject: [PATCH] Fix precedence by reordering grammar rule Signed-off-by: Chen Dai --- sql/src/main/antlr/OpenSearchSQLParser.g4 | 9 ++++----- .../sql/sql/parser/AstExpressionBuilder.java | 2 +- .../sql/sql/parser/AstExpressionBuilderTest.java | 11 +++++++++++ 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/sql/src/main/antlr/OpenSearchSQLParser.g4 b/sql/src/main/antlr/OpenSearchSQLParser.g4 index 58d4be1813..e24d38e093 100644 --- a/sql/src/main/antlr/OpenSearchSQLParser.g4 +++ b/sql/src/main/antlr/OpenSearchSQLParser.g4 @@ -292,11 +292,10 @@ expressionAtom | columnName #fullColumnNameExpressionAtom | functionCall #functionCallExpressionAtom | LR_BRACKET expression RR_BRACKET #nestedExpressionAtom - | left=expressionAtom mathOperator right=expressionAtom #mathExpressionAtom - ; - -mathOperator - : PLUS | MINUS | STAR | DIVIDE | MODULE + | left=expressionAtom mathOperator=(STAR | DIVIDE | MODULE) + right=expressionAtom #mathExpressionAtom + | left=expressionAtom mathOperator=(PLUS | MINUS) + right=expressionAtom #mathExpressionAtom ; comparisonOperator diff --git a/sql/src/main/java/org/opensearch/sql/sql/parser/AstExpressionBuilder.java b/sql/src/main/java/org/opensearch/sql/sql/parser/AstExpressionBuilder.java index bae22595ca..4b1a15425c 100644 --- a/sql/src/main/java/org/opensearch/sql/sql/parser/AstExpressionBuilder.java +++ b/sql/src/main/java/org/opensearch/sql/sql/parser/AstExpressionBuilder.java @@ -120,7 +120,7 @@ public UnresolvedExpression visitQualifiedName(QualifiedNameContext ctx) { @Override public UnresolvedExpression visitMathExpressionAtom(MathExpressionAtomContext ctx) { return new Function( - ctx.mathOperator().getText(), + ctx.mathOperator.getText(), Arrays.asList(visit(ctx.left), visit(ctx.right)) ); } diff --git a/sql/src/test/java/org/opensearch/sql/sql/parser/AstExpressionBuilderTest.java b/sql/src/test/java/org/opensearch/sql/sql/parser/AstExpressionBuilderTest.java index 9af4119fdf..384e8765d9 100644 --- a/sql/src/test/java/org/opensearch/sql/sql/parser/AstExpressionBuilderTest.java +++ b/sql/src/test/java/org/opensearch/sql/sql/parser/AstExpressionBuilderTest.java @@ -153,6 +153,17 @@ public void canBuildArithmeticExpression() { ); } + @Test + public void canBuildArithmeticExpressionWithPrecedence() { + assertEquals( + function("+", + intLiteral(1), + function("*", + intLiteral(2), intLiteral(3))), + buildExprAst("1 + 2 * 3") + ); + } + @Test public void canBuildFunctionWithoutArguments() { assertEquals(