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

Make Groovy Parser correctly handle nested parenthesis #4801

Merged
merged 22 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -720,4 +720,14 @@ public static String formatUriForPropertiesFile(String uri) {
public static boolean hasLineBreak(@Nullable String s) {
return s != null && LINE_BREAK.matcher(s).find();
}

public static boolean containsWhitespace(String s) {
for (int i = 0; i < s.length(); ++i) {
if (Character.isWhitespace(s.charAt(i))) {
return true;
}
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.EncodingDetectingInputStream;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.internal.JavaTypeCache;
import org.openrewrite.java.marker.ImplicitReturn;
import org.openrewrite.java.marker.OmitParentheses;
Expand Down Expand Up @@ -762,8 +763,11 @@ private <T> List<JRightPadded<T>> visitRightPadded(ASTNode[] nodes, @Nullable St
}

private Expression insideParentheses(ASTNode node, Function<Space, Expression> parenthesizedTree) {
int saveCursor = cursor;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
whitespace();
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
Integer insideParenthesesLevel = getInsideParenthesesLevel(node);
if (insideParenthesesLevel != null) {
cursor = saveCursor;
if (insideParenthesesLevel != null && insideParenthesesLevel > 0) {
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
Stack<Space> openingParens = new Stack<>();
for (int i = 0; i < insideParenthesesLevel; i++) {
openingParens.push(sourceBefore("("));
Expand All @@ -774,6 +778,8 @@ private Expression insideParentheses(ASTNode node, Function<Space, Expression> p
padRight(parenthesized, sourceBefore(")")));
}
return parenthesized;
} else {
cursor = saveCursor;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
}
return parenthesizedTree.apply(whitespace());
}
Expand Down Expand Up @@ -1350,20 +1356,20 @@ public void visitConstantExpression(ConstantExpression expression) {
jType = JavaType.Primitive.Short;
} else if (type == ClassHelper.STRING_TYPE) {
jType = JavaType.Primitive.String;
// String literals value returned by getValue()/getText() has already processed sequences like "\\" -> "\"
int length = sourceLengthOfString(expression);
// this is an attribute selector
if (source.startsWith("@" + value, cursor)) {
length += 1;
boolean attributeSelector = source.startsWith("@" + value, cursor);
int length = lengthAccordingToAst(expression);
Integer insideParenthesesLevel = getInsideParenthesesLevel(expression);
jevanlingen marked this conversation as resolved.
Show resolved Hide resolved
if (insideParenthesesLevel != null) {
length = length - insideParenthesesLevel * 2;
}
text = source.substring(cursor, cursor + length);
int delimiterLength = 0;
if (text.startsWith("$/")) {
delimiterLength = 2;
} else if (text.startsWith("\"\"\"") || text.startsWith("'''")) {
delimiterLength = 3;
} else if (text.startsWith("/") || text.startsWith("\"") || text.startsWith("'")) {
delimiterLength = 1;
String valueAccordingToAST = source.substring(cursor, cursor + length + (attributeSelector ? 1 : 0));
int delimiterLength = getDelimiterLength();
if (StringUtils.containsWhitespace(valueAccordingToAST)) {
length = delimiterLength + ((String) expression.getValue()).length() + delimiterLength;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
text = source.substring(cursor, cursor + length + (attributeSelector ? 1 : 0));
} else {
text = valueAccordingToAST;
}
value = text.substring(delimiterLength, text.length() - delimiterLength);
} else if (expression.isNullExpression()) {
Expand Down Expand Up @@ -2522,14 +2528,34 @@ private int sourceLengthOfString(ConstantExpression expr) {
return lengthAccordingToAst;
}

private static @Nullable Integer getInsideParenthesesLevel(ASTNode node) {
private @Nullable Integer getInsideParenthesesLevel(ASTNode node) {
Object rawIpl = node.getNodeMetaData("_INSIDE_PARENTHESES_LEVEL");
if (rawIpl instanceof AtomicInteger) {
// On Java 11 and newer _INSIDE_PARENTHESES_LEVEL is an AtomicInteger
return ((AtomicInteger) rawIpl).get();
} else {
} else if (rawIpl instanceof Integer) {
// On Java 8 _INSIDE_PARENTHESES_LEVEL is a regular Integer
return (Integer) rawIpl;
} else if (node instanceof MethodCallExpression) {
MethodCallExpression expr = (MethodCallExpression) node;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
int childBegin = cursor;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
if (expr.getObjectExpression().getLineNumber() != expr.getLineNumber()) {
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
for (int i = 0; i < (expr.getObjectExpression().getLineNumber() - expr.getLineNumber()) - 1; i++) {
childBegin = source.indexOf('\n', childBegin);
}
childBegin += expr.getObjectExpression().getColumnNumber();
} else {
childBegin += expr.getObjectExpression().getColumnNumber() - expr.getColumnNumber();
}
int count = 0;
for (int i = cursor; i < childBegin; i++) {
if (source.charAt(i) == '(') {
count++;
}
}
return count;
} else {
return null;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*/
package org.openrewrite.groovy.tree;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openrewrite.Issue;
import org.openrewrite.test.RewriteTest;
Expand All @@ -34,6 +33,7 @@ void insideParentheses() {

// NOT inside parentheses, but verifies the parser's
// test for "inside parentheses" condition
groovy("( 1 ) + 1"),
groovy("(1) + 1"),
// And combine the two cases
groovy("((1) + 1)")
Expand Down Expand Up @@ -216,6 +216,35 @@ void stringMultipliedInParentheses() {
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/4703")
@Test
void cxds() {
rewriteRun(
groovy(
"""
def differenceInDays(int time) {
return (int) ((time)/(1000*60*60*24))
}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/4703")
@Test
void extraParensAroundInfixOxxxperator() {
rewriteRun(
groovy(
"""
def timestamp(int hours, int minutes, int seconds) {
30 * (hours)
(((((hours))))) * 30
}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/4703")
@Test
void extraParensAroundInfixOperator() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package org.openrewrite.groovy.tree;

import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ExpectedToFail;
import org.openrewrite.Issue;
import org.openrewrite.test.RewriteTest;

Expand All @@ -25,6 +24,18 @@
@SuppressWarnings({"UnnecessaryQualifiedReference", "GroovyUnusedAssignment", "GrUnnecessarySemicolon"})
class CastTest implements RewriteTest {

@Test
void javaStyleCastNew() {
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
rewriteRun(
groovy(
"""
String foo = ( String ) "hallo"
String bar = "hallo" as String
"""
)
);
}

@Test
void javaStyleCast() {
rewriteRun(
Expand Down Expand Up @@ -74,14 +85,13 @@ void groovyCastAndInvokeMethod() {
rewriteRun(
groovy(
"""
( "" as String ).toString()
( "x" as String ).toString()
"""
)
);
}

@Test
@ExpectedToFail("Parentheses with method invocation is not yet supported")
void groovyCastAndInvokeMethodWithParentheses() {
rewriteRun(
groovy(
Expand All @@ -103,7 +113,6 @@ void javaCastAndInvokeMethod() {
);
}

@ExpectedToFail("Parentheses with method invocation is not yet supported")
@Test
void javaCastAndInvokeMethodWithParentheses() {
rewriteRun(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package org.openrewrite.groovy.tree;

import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ExpectedToFail;
import org.openrewrite.Issue;
import org.openrewrite.test.RewriteTest;

Expand All @@ -31,11 +30,11 @@ void gradle() {
plugins {
id 'java-library'
}

repositories {
mavenCentral()
}

dependencies {
implementation 'org.hibernate:hibernate-core:3.6.7.Final'
api 'com.google.guava:guava:23.0'
Expand All @@ -46,7 +45,6 @@ void gradle() {
);
}

@ExpectedToFail("Parentheses with method invocation is not yet supported")
@Test
@Issue("https://github.com/openrewrite/rewrite/issues/4615")
void gradleWithParentheses() {
Expand Down Expand Up @@ -349,7 +347,7 @@ class StringUtils {
static boolean isEmpty(String value) {
return value == null || value.isEmpty()
}

static void main(String[] args) {
isEmpty("")
}
Expand All @@ -359,7 +357,29 @@ static void main(String[] args) {
);
}

@ExpectedToFail("Parentheses with method invocation is not yet supported")
@Issue("https://github.com/openrewrite/rewrite/issues/4703")
@Test
void insideParenthesesSimple() {
rewriteRun(
groovy(
"""
((a.invoke "b" ))
"""
)
);
}

@Test
void lotOfSpacesAroundConstantWithParentheses() {
rewriteRun(
groovy(
"""
( ( ( "x" ) ).toString() )
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/4703")
@Test
void insideParentheses() {
Expand All @@ -375,7 +395,6 @@ static def foo(Map map) {
);
}

@ExpectedToFail("Parentheses with method invocation is not yet supported")
@Issue("https://github.com/openrewrite/rewrite/issues/4703")
@Test
void insideParenthesesWithoutNewLineAndEscapedMethodName() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package org.openrewrite.groovy.tree;

import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ExpectedToFail;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.groovy.Assertions.groovy;
Expand Down Expand Up @@ -48,7 +47,6 @@ void parenthesized() {
);
}

@ExpectedToFail("Parentheses with method invocation is not yet supported")
@Test
void parenthesizedAndInvokeMethodWithParentheses() {
rewriteRun(
Expand Down
Loading