diff --git a/rewrite-groovy/src/main/java/org/openrewrite/groovy/format/AutoFormatVisitor.java b/rewrite-groovy/src/main/java/org/openrewrite/groovy/format/AutoFormatVisitor.java index 250b316cd9..1d40de96f3 100644 --- a/rewrite-groovy/src/main/java/org/openrewrite/groovy/format/AutoFormatVisitor.java +++ b/rewrite-groovy/src/main/java/org/openrewrite/groovy/format/AutoFormatVisitor.java @@ -27,7 +27,6 @@ import org.openrewrite.style.Style; import java.util.Optional; -import java.util.function.Supplier; import static org.openrewrite.java.format.AutodetectGeneralFormatStyle.autodetectGeneralFormatStyle; @@ -58,17 +57,20 @@ public J visit(@Nullable Tree tree, P p, Cursor cursor) { t = new WrappingAndBracesVisitor<>(Style.from(WrappingAndBracesStyle.class, cu, IntelliJ::wrappingAndBraces), stopAfter) .visit(t, p, cursor.fork()); + TabsAndIndentsStyle tabsAndIndentsStyle = Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents); + SpacesStyle spacesStyle = Style.from(SpacesStyle.class, cu, IntelliJ::spaces); + t = new SpacesVisitor<>( - Style.from(SpacesStyle.class, cu, IntelliJ::spaces), + spacesStyle, cu.getStyle(EmptyForInitializerPadStyle.class), Style.from(EmptyForIteratorPadStyle.class, cu), stopAfter ).visit(t, p, cursor.fork()); - t = new NormalizeTabsOrSpacesVisitor<>(Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents), stopAfter) + t = new NormalizeTabsOrSpacesVisitor<>(tabsAndIndentsStyle, stopAfter) .visit(t, p, cursor.fork()); - t = new TabsAndIndentsVisitor<>(Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents), stopAfter) + t = new TabsAndIndentsVisitor<>(tabsAndIndentsStyle, spacesStyle, stopAfter) .visit(t, p, cursor.fork()); t = new NormalizeLineBreaksVisitor<>(Optional.ofNullable(Style.from(GeneralFormatStyle.class, cu)) diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/format/TabsAndIndentsTest.java b/rewrite-java-test/src/test/java/org/openrewrite/java/format/TabsAndIndentsTest.java index b4bd072100..c695bc4a50 100644 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/format/TabsAndIndentsTest.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/format/TabsAndIndentsTest.java @@ -35,12 +35,7 @@ import static java.util.Collections.singletonList; import static org.openrewrite.java.Assertions.java; -@SuppressWarnings({ - "InfiniteRecursion", "UnusedAssignment", "ConstantConditions", "StatementWithEmptyBody", "RedundantThrows", - "UnusedLabel", "SwitchStatementWithTooFewBranches", "InfiniteLoopStatement", "rawtypes", "ResultOfMethodCallIgnored", - "CodeBlock2Expr", "DuplicateThrows", "EmptyTryBlock", "CatchMayIgnoreException", "EmptyFinallyBlock", - "PointlessBooleanExpression", "ClassInitializerMayBeStatic", "MismatchedReadAndWriteOfArray" - , "TypeParameterExplicitlyExtendsObject"}) +@SuppressWarnings({"InfiniteRecursion", "UnusedAssignment", "ConstantConditions", "StatementWithEmptyBody", "RedundantThrows", "UnusedLabel", "SwitchStatementWithTooFewBranches", "InfiniteLoopStatement", "rawtypes", "ResultOfMethodCallIgnored", "CodeBlock2Expr", "DuplicateThrows", "EmptyTryBlock", "CatchMayIgnoreException", "EmptyFinallyBlock", "PointlessBooleanExpression", "ClassInitializerMayBeStatic", "MismatchedReadAndWriteOfArray", "TypeParameterExplicitlyExtendsObject", "CallToPrintStackTrace"}) class TabsAndIndentsTest implements RewriteTest { @Override @@ -59,10 +54,10 @@ void rspec3973() { class Test {{ if (true == false) doTheThing(); - + doTheOtherThing(); somethingElseEntirely(); - + foo(); } public static void doTheThing() {} @@ -75,10 +70,10 @@ public static void foo() {} class Test {{ if (true == false) doTheThing(); - + doTheOtherThing(); somethingElseEntirely(); - + foo(); } public static void doTheThing() {} @@ -95,7 +90,7 @@ private static Consumer tabsAndIndents(UnaryOperator spec.recipe(new TabsAndIndents()) .parser(JavaParser.fromJavaVersion().styles(singletonList( new NamedStyles( - Tree.randomId(), "test", "test", "test", emptySet(), + Tree.randomId(), "test", "Test", "Test", emptySet(), singletonList(with.apply(IntelliJ.tabsAndIndents())) ) ))); @@ -531,7 +526,7 @@ void method(Collection> c) { return 0; }) ) - .collect(Collectors.toList()); + .toList(); } } """ @@ -553,7 +548,7 @@ void method(Collection> c) { 0 ) ) - .collect(Collectors.toList()); + .toList(); } } """ @@ -979,7 +974,7 @@ class Test { static { System.out.println("hi"); } - + { } } @@ -1223,6 +1218,7 @@ public void test(boolean a, int x, int y) { } @Test + @SuppressWarnings("DuplicateCondition") void nestedIfElse() { rewriteRun( java( @@ -1264,7 +1260,7 @@ void newClassAsMethodArgument() { class Test { Test(String s, int m) { } - + void method(Test t) { method(new Test("hello" + "world", @@ -1290,20 +1286,20 @@ void method(int n, File f, int m, int l) { m, l); } - + void method2(int n, File f, int m) { method(n, new File( "test" ), m, 0); } - + void method3(int n, File f) { method2(n, new File( "test" ), 0); } - + void method4(int n) { method3(n, new File( "test" @@ -1433,13 +1429,13 @@ class Test { void method() throws IOException, Exception { } - + void method2() throws IOException, Exception { } } - """ + """ ) ); } @@ -1539,7 +1535,7 @@ void containers() { throws Exception { try (InputStream is = new ByteArrayInputStream(new byte[0])) {} - int n[] = + int n[] = {0}; switch (1) { case 1: @@ -1570,7 +1566,7 @@ void containers() { throws Exception { try (InputStream is = new ByteArrayInputStream(new byte[0])) {} - int n[] = + int n[] = {0}; switch (1) { case 1: @@ -1597,7 +1593,7 @@ Test method(int n) { .method(n) .method(n); } - + Test method2() { return method2(). method2(). @@ -1664,7 +1660,7 @@ void variableWithAnnotation() { public class Test { @Deprecated final String scope; - + @Deprecated String classifier; } @@ -1708,7 +1704,7 @@ abstract class Test { abstract Test a(Function f); abstract Test b(Function f); abstract Test c(Function f); - + Test method(Function f) { return a(f) .b(t -> @@ -1892,7 +1888,7 @@ void alignLineComments() { """ // shift left. package org.openrewrite; // trailing comment. - + // shift left. public class A { // trailing comment at class. // shift right. @@ -1902,8 +1898,8 @@ public int method(int value) { // trailing comment at method. // shift left. if (value == 1) { // trailing comment at if. // suffix contains new lines with whitespace. - - + + // shift right. // shift left. value += 10; // trailing comment. @@ -1914,12 +1910,12 @@ public int method(int value) { // trailing comment at method. // shift right at end of block. // shift left at end of block. } - + if (value == 11) // shift right. // shift left. value += 1; - + return value; // shift right at end of block. // shift left at end of block. @@ -1931,7 +1927,7 @@ public int method(int value) { // trailing comment at method. """ // shift left. package org.openrewrite; // trailing comment. - + // shift left. public class A { // trailing comment at class. // shift right. @@ -1941,8 +1937,8 @@ public int method(int value) { // trailing comment at method. // shift left. if (value == 1) { // trailing comment at if. // suffix contains new lines with whitespace. - - + + // shift right. // shift left. value += 10; // trailing comment. @@ -1953,12 +1949,12 @@ public int method(int value) { // trailing comment at method. // shift right at end of block. // shift left at end of block. } - + if (value == 11) // shift right. // shift left. value += 1; - + return value; // shift right at end of block. // shift left at end of block. @@ -2043,22 +2039,22 @@ public class Test { public void method() { // inline try, catch, finally. try { - + } catch (Exception ex) { - + } finally { - + } - + // new line try, catch, finally. try { - + } catch (Exception ex) { - + } finally { - + } } } @@ -2075,7 +2071,7 @@ void alignBlockPrefixes() { java( """ public class Test { - + public void practiceA() { for (int i = 0; i < 10; ++i) @@ -2097,7 +2093,7 @@ public void practiceA() } } } - + public void practiceB() { for (int i = 0; i < 10; ++i) { if (i % 2 == 0) { @@ -2253,7 +2249,7 @@ public class A { public int methodOne(int value) { return value + 1; } - + /** Edge case formatting test. @param value test value. @return value + 1 @@ -2274,7 +2270,7 @@ public class A { public int methodOne(int value) { return value + 1; } - + /** Edge case formatting test. @param value test value. @return value + 1 @@ -2433,4 +2429,78 @@ String test() { ) ); } + + @Test + void tryWithResourcesMultipleResourcesOnMultipleLines() { + rewriteRun( + java( + """ + import java.io.*; + class Test { + void method(String file1, String file2) { + try (FileInputStream fis1 = new FileInputStream(file1); + FileInputStream fis2 = new FileInputStream(file2); + BufferedInputStream bis = new BufferedInputStream(fis1)) { + // process files + } catch (IOException e) { + e.printStackTrace(); + } + } + } + """, + """ + import java.io.*; + class Test { + void method(String file1, String file2) { + try (FileInputStream fis1 = new FileInputStream(file1); + FileInputStream fis2 = new FileInputStream(file2); + BufferedInputStream bis = new BufferedInputStream(fis1)) { + // process files + } catch (IOException e) { + e.printStackTrace(); + } + } + } + """ + ) + ); + } + + @Test + void tryWithResourcesFirstResourceOnNewLine() { + rewriteRun( + java( + """ + import java.io.*; + class Test { + void method(String file1, String file2) { + try ( + FileInputStream fis1 = new FileInputStream(file1); + FileInputStream fis2 = new FileInputStream(file2); + BufferedInputStream bis = new BufferedInputStream(fis1)) { + // process files + } catch (IOException e) { + e.printStackTrace(); + } + } + } + """, + """ + import java.io.*; + class Test { + void method(String file1, String file2) { + try ( + FileInputStream fis1 = new FileInputStream(file1); + FileInputStream fis2 = new FileInputStream(file2); + BufferedInputStream bis = new BufferedInputStream(fis1)) { + // process files + } catch (IOException e) { + e.printStackTrace(); + } + } + } + """ + ) + ); + } } diff --git a/rewrite-java/src/main/java/org/openrewrite/java/format/AutoFormatVisitor.java b/rewrite-java/src/main/java/org/openrewrite/java/format/AutoFormatVisitor.java index d9b8753796..da7c5db6ea 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/format/AutoFormatVisitor.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/format/AutoFormatVisitor.java @@ -27,7 +27,6 @@ import org.openrewrite.style.Style; import java.util.Optional; -import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static org.openrewrite.java.format.AutodetectGeneralFormatStyle.autodetectGeneralFormatStyle; @@ -65,17 +64,20 @@ public J visit(@Nullable Tree tree, P p, Cursor cursor) { t = new WrappingAndBracesVisitor<>(Style.from(WrappingAndBracesStyle.class, cu, IntelliJ::wrappingAndBraces), stopAfter) .visit(t, p, cursor.fork()); + SpacesStyle spacesStyle = Style.from(SpacesStyle.class, cu, IntelliJ::spaces); + TabsAndIndentsStyle tabsAndIndentsStyle = Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents); + t = new SpacesVisitor<>( - Style.from(SpacesStyle.class, cu, IntelliJ::spaces), + spacesStyle, Style.from(EmptyForInitializerPadStyle.class, cu), Style.from(EmptyForIteratorPadStyle.class, cu), stopAfter ).visit(t, p, cursor.fork()); - t = new NormalizeTabsOrSpacesVisitor<>(Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents), stopAfter) + t = new NormalizeTabsOrSpacesVisitor<>(tabsAndIndentsStyle, stopAfter) .visit(t, p, cursor.fork()); - t = new TabsAndIndentsVisitor<>(Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents), stopAfter) + t = new TabsAndIndentsVisitor<>(tabsAndIndentsStyle, spacesStyle, stopAfter) .visit(t, p, cursor.fork()); t = new NormalizeLineBreaksVisitor<>(Optional.ofNullable(Style.from(GeneralFormatStyle.class, cu)) @@ -102,8 +104,10 @@ public J visit(@Nullable Tree tree, P p) { t = (JavaSourceFile) new BlankLinesVisitor<>(Style.from(BlankLinesStyle.class, cu, IntelliJ::blankLines), stopAfter) .visit(t, p); - t = (JavaSourceFile) new SpacesVisitor

(Optional.ofNullable( - Style.from(SpacesStyle.class, cu)).orElse(IntelliJ.spaces()), + SpacesStyle spacesStyle = Optional.ofNullable(Style.from(SpacesStyle.class, cu)).orElse(IntelliJ.spaces()); + TabsAndIndentsStyle tabsAndIndentsStyle = Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents); + + t = (JavaSourceFile) new SpacesVisitor

(spacesStyle, Style.from(EmptyForInitializerPadStyle.class, cu), Style.from(EmptyForIteratorPadStyle.class, cu), stopAfter) @@ -112,10 +116,10 @@ public J visit(@Nullable Tree tree, P p) { t = (JavaSourceFile) new WrappingAndBracesVisitor<>(Style.from(WrappingAndBracesStyle.class, cu, IntelliJ::wrappingAndBraces), stopAfter) .visit(t, p); - t = (JavaSourceFile) new NormalizeTabsOrSpacesVisitor<>(Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents), stopAfter) + t = (JavaSourceFile) new NormalizeTabsOrSpacesVisitor<>(tabsAndIndentsStyle, stopAfter) .visit(t, p); - t = (JavaSourceFile) new TabsAndIndentsVisitor<>(Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents), stopAfter) + t = (JavaSourceFile) new TabsAndIndentsVisitor<>(tabsAndIndentsStyle, spacesStyle, stopAfter) .visit(t, p); assert t != null; diff --git a/rewrite-java/src/main/java/org/openrewrite/java/format/ColumnPositionCalculator.java b/rewrite-java/src/main/java/org/openrewrite/java/format/ColumnPositionCalculator.java new file mode 100644 index 0000000000..9a917aba81 --- /dev/null +++ b/rewrite-java/src/main/java/org/openrewrite/java/format/ColumnPositionCalculator.java @@ -0,0 +1,68 @@ +/* + * Copyright 2025 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openrewrite.java.format; + +import org.jspecify.annotations.Nullable; +import org.openrewrite.Cursor; +import org.openrewrite.PrintOutputCapture; +import org.openrewrite.TreeVisitor; +import org.openrewrite.internal.RecipeRunException; +import org.openrewrite.java.tree.J; + +import java.util.concurrent.CancellationException; + +/** + * Utility class for computing column positions of elements within a Java AST. + */ +class ColumnPositionCalculator { + + /** + * Computes the column position of a target element within a tree by printing the tree + * up to the target element and counting characters from the last newline. + * + * @param tree The tree to print + * @param targetElement The element whose column position we want to find + * @param cursor The cursor context + * @return The column position of the target element + */ + public static int computeColumnPosition(J tree, J targetElement, Cursor cursor) { + TreeVisitor>> printer = tree.printer(cursor); + PrintOutputCapture> capture = new PrintOutputCapture>(printer) { + @Override + public PrintOutputCapture> append(@Nullable String text) { + if (targetElement.isScope(getContext().getCursor().getValue())) { + throw new CancellationException(); + } + return super.append(text); + } + }; + try { + printer.visit(tree, capture, cursor.getParentOrThrow()); + throw new IllegalStateException("Target element not found in tree"); + } catch (CancellationException ignored) { + String out = capture.getOut(); + int lineBreakIndex = out.lastIndexOf('\n'); + return (out.length() - (lineBreakIndex == -1 ? 0 : lineBreakIndex)) - 1; + } catch (RecipeRunException e) { + if (e.getCause() instanceof CancellationException) { + String out = capture.getOut(); + int lineBreakIndex = out.lastIndexOf('\n'); + return (out.length() - (lineBreakIndex == -1 ? 0 : lineBreakIndex)) - 1; + } + throw e; + } + } +} diff --git a/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndents.java b/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndents.java index d3034d21bb..cda71d9577 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndents.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndents.java @@ -19,9 +19,13 @@ import org.openrewrite.*; import org.openrewrite.java.JavaIsoVisitor; import org.openrewrite.java.style.IntelliJ; +import org.openrewrite.java.style.SpacesStyle; import org.openrewrite.java.style.TabsAndIndentsStyle; import org.openrewrite.java.tree.J; import org.openrewrite.java.tree.JavaSourceFile; +import org.openrewrite.style.Style; + +import java.util.Optional; import static java.util.Objects.requireNonNull; @@ -46,21 +50,20 @@ private static class TabsAndIndentsFromCompilationUnitStyle extends JavaIsoVisit public J visit(@Nullable Tree tree, ExecutionContext ctx) { if (tree instanceof JavaSourceFile) { JavaSourceFile cu = (JavaSourceFile) requireNonNull(tree); - TabsAndIndentsStyle style = ((SourceFile) cu).getStyle(TabsAndIndentsStyle.class); - if (style == null) { - style = IntelliJ.tabsAndIndents(); - } - return new TabsAndIndentsVisitor<>(style).visit(tree, ctx); + TabsAndIndentsStyle style = Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents); + SpacesStyle spacesStyle = Optional.ofNullable(Style.from(SpacesStyle.class, cu)).orElse(IntelliJ.spaces()); + return new TabsAndIndentsVisitor<>(style, spacesStyle).visit(tree, ctx); } return (J) tree; } } public static J2 formatTabsAndIndents(J j, Cursor cursor) { - TabsAndIndentsStyle style = cursor.firstEnclosingOrThrow(SourceFile.class) - .getStyle(TabsAndIndentsStyle.class); + SourceFile cu = cursor.firstEnclosingOrThrow(SourceFile.class); + TabsAndIndentsStyle style = Style.from(TabsAndIndentsStyle.class, cu, IntelliJ::tabsAndIndents); + SpacesStyle spacesStyle = Optional.ofNullable(Style.from(SpacesStyle.class, cu)).orElse(IntelliJ.spaces()); //noinspection unchecked - return (J2) new TabsAndIndentsVisitor<>(style == null ? IntelliJ.tabsAndIndents() : style) + return (J2) new TabsAndIndentsVisitor<>(style, spacesStyle) .visitNonNull(j, 0, cursor); } } diff --git a/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java b/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java index 33c977107f..7593852fa6 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/format/TabsAndIndentsVisitor.java @@ -17,32 +17,33 @@ import org.jspecify.annotations.Nullable; import org.openrewrite.Cursor; -import org.openrewrite.PrintOutputCapture; import org.openrewrite.Tree; -import org.openrewrite.TreeVisitor; import org.openrewrite.internal.ListUtils; -import org.openrewrite.internal.RecipeRunException; import org.openrewrite.internal.StringUtils; import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.style.SpacesStyle; import org.openrewrite.java.style.TabsAndIndentsStyle; import org.openrewrite.java.tree.*; import java.util.Iterator; import java.util.List; -import java.util.concurrent.CancellationException; + +import static org.openrewrite.java.format.ColumnPositionCalculator.computeColumnPosition; public class TabsAndIndentsVisitor

extends JavaIsoVisitor

{ @Nullable private final Tree stopAfter; private final TabsAndIndentsStyle style; + private final SpacesStyle spacesStyle; - public TabsAndIndentsVisitor(TabsAndIndentsStyle style) { - this(style, null); + public TabsAndIndentsVisitor(TabsAndIndentsStyle style, SpacesStyle spacesStyle) { + this(style, spacesStyle, null); } - public TabsAndIndentsVisitor(TabsAndIndentsStyle style, @Nullable Tree stopAfter) { + public TabsAndIndentsVisitor(TabsAndIndentsStyle style, SpacesStyle spacesStyle, @Nullable Tree stopAfter) { this.style = style; + this.spacesStyle = spacesStyle; this.stopAfter = stopAfter; } @@ -296,6 +297,40 @@ public Space visitSpace(Space space, Space.Location loc, P p) { after = visitSpace(right.getAfter(), loc.getAfterLocation(), p); break; + case TRY_RESOURCE: + // Align subsequent resources with the first resource in try-with-resources + JContainer resources = getCursor().getParentOrThrow().getValue(); + List> resourceElements = resources.getPadding().getElements(); + if (resourceElements.size() > 1 && resourceElements.get(0) != right && elem.getPrefix().getLastWhitespace().contains("\n")) { + // For resources after the first one, align with the first resource + J firstResource = resourceElements.get(0).getElement(); + if (!firstResource.getPrefix().getLastWhitespace().contains("\n")) { + // First resource is on the same line as try( + // We need to calculate the indent based on the try statement position + // For now, let's use a simplified approach - align with the opening parenthesis + // Count the column position by looking at the try statement prefix and "try (" + J.Try tryStatement = getCursor().firstEnclosing(J.Try.class); + String tryPrefix = tryStatement.getPrefix().getWhitespace(); + int tryIndent = getLengthOfWhitespace(tryPrefix.substring(tryPrefix.lastIndexOf('\n') + 1)); + // Add 3 for "try" and 1 for "(" and optionally one for space in between + int firstResourceColumn = tryIndent + 4 + (spacesStyle.getBeforeParentheses().getTryParentheses() ? 1 : 0); + elem = elem.withPrefix(indentTo(elem.getPrefix(), firstResourceColumn, Space.Location.TRY_RESOURCE)); + elem = visitAndCast(elem, p); + after = right.getAfter(); + } else { + // First resource is on a new line, align with it + String firstResourcePrefix = firstResource.getPrefix().getWhitespace(); + int firstResourceIndent = getLengthOfWhitespace(firstResourcePrefix.substring(firstResourcePrefix.lastIndexOf('\n') + 1)); + elem = elem.withPrefix(indentTo(elem.getPrefix(), firstResourceIndent, Space.Location.TRY_RESOURCE)); + elem = visitAndCast(elem, p); + after = right.getAfter(); + } + } else { + // For the first resource or single resource, use default handling + elem = visitAndCast(elem, p); + after = visitSpace(right.getAfter(), loc.getAfterLocation(), p); + } + break; default: elem = visitAndCast(elem, p); after = visitSpace(right.getAfter(), loc.getAfterLocation(), p); @@ -364,24 +399,7 @@ private int computeFirstParameterColumn(J.MethodDeclaration method) { if (firstArg.getPrefix().getLastWhitespace().contains("\n")) { return getLengthOfWhitespace(firstArg.getPrefix().getLastWhitespace()); } else { - TreeVisitor>> printer = method.printer(getCursor()); - PrintOutputCapture> capture = new PrintOutputCapture>(printer) { - @Override - public PrintOutputCapture> append(@Nullable String text) { - if (getContext().getCursor().getValue() == firstArg) { - throw new CancellationException(); - } - return super.append(text); - } - }; - try { - printer.visit(method, capture, getCursor().getParentOrThrow()); - throw new IllegalStateException(); - } catch (RecipeRunException e) { - String out = capture.getOut(); - int lineBreakIndex = out.lastIndexOf('\n'); - return (out.length() - (lineBreakIndex == -1 ? 0 : lineBreakIndex)) - 1; - } + return computeColumnPosition(method, firstArg, getCursor()); } }