Skip to content
Merged
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
105 changes: 105 additions & 0 deletions src/main/java/org/checkstyle/autofix/PositionHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle-openrewrite-recipes: Automatically fix Checkstyle violations with OpenRewrite.
// Copyright (C) 2025 The Checkstyle OpenRewrite Recipes 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
//
// http://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.checkstyle.autofix;

import java.util.concurrent.CancellationException;
import java.util.function.Function;

import org.openrewrite.Cursor;
import org.openrewrite.PrintOutputCapture;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.RecipeRunException;
import org.openrewrite.java.tree.J;

public final class PositionHelper {

private PositionHelper() {
// Utility class
}

public static int computeLinePosition(J tree, J targetElement, Cursor cursor) {
return computePosition(tree, targetElement, cursor,
out -> 1 + Math.toIntExact(out.chars().filter(chr -> chr == '\n').count()));
}

public static int computeColumnPosition(J tree, J targetElement, Cursor cursor) {
return computePosition(tree, targetElement, cursor, out -> {
int column = calculateColumnOffset(out);
if (targetElement instanceof J.Literal literal
&& literal.getValue() instanceof Number
&& literal.getValueSource() != null
&& literal.getValueSource().matches("^[+-].*")) {
column++;
}
return column;
});
}

private static int computePosition(
J tree,
J targetElement,
Cursor cursor,
Function<String, Integer> positionCalculator
) {
final TreeVisitor<?, PrintOutputCapture<TreeVisitor<?, ?>>> printer =
tree.printer(cursor);

final PrintOutputCapture<TreeVisitor<?, ?>> capture =
new PrintOutputCapture<>(printer) {
@Override
public PrintOutputCapture<TreeVisitor<?, ?>> append(String text) {
if (targetElement.isScope(getContext().getCursor().getValue())) {
super.append(targetElement.getPrefix().getWhitespace());
throw new CancellationException();
}
return super.append(text);
}
};

final int result;
try {
printer.visit(tree, capture, cursor.getParentOrThrow());
throw new IllegalStateException("Target element: " + targetElement
+ ", not found in the syntax tree.");
}
catch (CancellationException exception) {
result = positionCalculator.apply(capture.getOut());
}
catch (RecipeRunException exception) {
if (exception.getCause() instanceof CancellationException) {
result = positionCalculator.apply(capture.getOut());
}
else {
throw exception;
}
}
return result;
}

private static int calculateColumnOffset(String out) {
final int lineBreakIndex = out.lastIndexOf('\n');
final int result;
if (lineBreakIndex == -1) {
result = out.length();
}
else {
result = out.length() - lineBreakIndex;
}
return result;
}
}
111 changes: 111 additions & 0 deletions src/main/java/org/checkstyle/autofix/recipe/FinalLocalVariable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle-openrewrite-recipes: Automatically fix Checkstyle violations with OpenRewrite.
// Copyright (C) 2025 The Checkstyle OpenRewrite Recipes 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
//
// http://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.checkstyle.autofix.recipe;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import org.checkstyle.autofix.PositionHelper;
import org.checkstyle.autofix.parser.CheckstyleViolation;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.Tree;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.Space;
import org.openrewrite.marker.Markers;

/**
* Fixes Checkstyle FinalLocalVariable violations by adding 'final' modifier to local variables
* that are never reassigned.
*/
public class FinalLocalVariable extends Recipe {

private final List<CheckstyleViolation> violations;

public FinalLocalVariable(List<CheckstyleViolation> violations) {
this.violations = violations;
}

@Override
public String getDisplayName() {
return "FinalLocalVariable recipe";
}

@Override
public String getDescription() {
return "Adds 'final' modifier to local variables that never have their values changed.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new LocalVariableVisitor();
}

private final class LocalVariableVisitor extends JavaIsoVisitor<ExecutionContext> {

private Path sourcePath;

@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
this.sourcePath = cu.getSourcePath();
return super.visitCompilationUnit(cu, ctx);
}

@Override
public J.VariableDeclarations visitVariableDeclarations(
J.VariableDeclarations multiVariable, ExecutionContext ctx) {

J.VariableDeclarations declarations = super.visitVariableDeclarations(multiVariable,
ctx);

if (!(getCursor().getParentTreeCursor().getValue() instanceof J.ClassDeclaration)
&& declarations.getVariables().size() == 1
&& declarations.getTypeExpression() != null
&& !declarations.hasModifier(J.Modifier.Type.Final)) {
final J.VariableDeclarations.NamedVariable variable = declarations
.getVariables().get(0);
if (isAtViolationLocation(variable)) {
final List<J.Modifier> modifiers = new ArrayList<>();
modifiers.add(new J.Modifier(Tree.randomId(), Space.EMPTY,
Markers.EMPTY, null, J.Modifier.Type.Final, new ArrayList<>()));
modifiers.addAll(declarations.getModifiers());
declarations = declarations.withModifiers(modifiers)
.withTypeExpression(declarations.getTypeExpression()
.withPrefix(Space.SINGLE_SPACE));
}
}
return declarations;
}

private boolean isAtViolationLocation(J.VariableDeclarations.NamedVariable literal) {
final J.CompilationUnit cursor = getCursor().firstEnclosing(J.CompilationUnit.class);

final int line = PositionHelper.computeLinePosition(cursor, literal, getCursor());
final int column = PositionHelper.computeColumnPosition(cursor, literal, getCursor());

return violations.stream().anyMatch(violation -> {
return violation.getLine() == line
&& violation.getColumn() == column
&& Path.of(violation.getFileName()).equals(sourcePath);
});
}
}
}
93 changes: 3 additions & 90 deletions src/main/java/org/checkstyle/autofix/recipe/UpperEll.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,12 @@

import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.function.Function;

import org.checkstyle.autofix.PositionHelper;
import org.checkstyle.autofix.parser.CheckstyleViolation;
import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.PrintOutputCapture;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.RecipeRunException;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
Expand Down Expand Up @@ -93,8 +89,8 @@ && isAtViolationLocation(result)) {
private boolean isAtViolationLocation(J.Literal literal) {
final J.CompilationUnit cursor = getCursor().firstEnclosing(J.CompilationUnit.class);

final int line = computeLinePosition(cursor, literal, getCursor());
final int column = computeColumnPosition(cursor, literal, getCursor());
final int line = PositionHelper.computeLinePosition(cursor, literal, getCursor());
final int column = PositionHelper.computeColumnPosition(cursor, literal, getCursor());

return violations.stream().anyMatch(violation -> {
final Path absolutePath = Path.of(violation.getFileName()).toAbsolutePath();
Expand All @@ -103,88 +99,5 @@ private boolean isAtViolationLocation(J.Literal literal) {
&& absolutePath.equals(sourcePath);
});
}

/**
* Computes the position of a target element within a syntax tree using position calculator.
* This method traverses the given syntax tree and captures the printed output until the
* target element is encountered. When the target is found, a CancellationException
* is thrown to interrupt traversal, and the captured output is passed to the provided
* positionCalculator to compute the position.
*
* @param tree the root of the syntax tree to traverse
* @param targetElement the element whose position is to be computed
* @param cursor the current cursor in the tree traversal
* @param positionCalculator a function to compute the position from the printed output
* @return the computed position of the target element
* @throws IllegalStateException if the target element is not found in the tree
* @throws RecipeRunException if an error occurs during traversal
*/
private int computePosition(
J tree,
J targetElement,
Cursor cursor,
Function<String, Integer> positionCalculator
) {
final TreeVisitor<?, PrintOutputCapture<TreeVisitor<?, ?>>> printer =
tree.printer(cursor);

final PrintOutputCapture<TreeVisitor<?, ?>> capture =
new PrintOutputCapture<>(printer) {
@Override
public PrintOutputCapture<TreeVisitor<?, ?>> append(String text) {
if (targetElement.isScope(getContext().getCursor().getValue())) {
super.append(targetElement.getPrefix().getWhitespace());
throw new CancellationException();
}
return super.append(text);
}
};

final int result;
try {
printer.visit(tree, capture, cursor.getParentOrThrow());
throw new IllegalStateException("Target element: " + targetElement
+ ", not found in the syntax tree.");
}
catch (CancellationException exception) {
result = positionCalculator.apply(capture.getOut());
}
catch (RecipeRunException exception) {
if (exception.getCause() instanceof CancellationException) {
result = positionCalculator.apply(capture.getOut());
}
else {
throw exception;
}
}
return result;
}

private int computeLinePosition(J tree, J targetElement, Cursor cursor) {
return computePosition(tree, targetElement, cursor,
out -> 1 + Math.toIntExact(out.chars().filter(chr -> chr == '\n').count()));
}

private int computeColumnPosition(J tree, J targetElement, Cursor cursor) {
return computePosition(tree, targetElement, cursor, out -> {
int column = calculateColumnOffset(out);
if (((J.Literal) targetElement).getValueSource().matches("^[+-].*")) {
column++;
}
return column;
});
}

private int calculateColumnOffset(String out) {
final int lineBreakIndex = out.lastIndexOf('\n');
final int result;
if (lineBreakIndex == -1) {
result = out.length();
}
else {
result = out.length() - lineBreakIndex;
}
return result;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle-openrewrite-recipes: Automatically fix Checkstyle violations with OpenRewrite.
// Copyright (C) 2025 The Checkstyle OpenRewrite Recipes 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
//
// http://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.checkstyle.autofix.recipe;

import java.util.List;

import org.checkstyle.autofix.parser.CheckConfiguration;
import org.checkstyle.autofix.parser.CheckstyleViolation;
import org.junit.jupiter.api.Test;
import org.openrewrite.Recipe;

public class FinalLocalVariableTest extends AbstractRecipeTestSupport {

@Override
protected String getSubpackage() {
return "finallocalvariable";
}

@Override
protected Recipe createRecipe(List<CheckstyleViolation> violations, CheckConfiguration config) {

return new FinalLocalVariable(violations);
}

@Test
void singleLocalTest() throws Exception {
verify("SingleLocalTest");
}

@Test
void classFieldTest() throws Exception {
verify("ClassFieldTest");
}

@Test
void edgeCaseTest() throws Exception {
verify("EdgeCaseTest");
}

@Test
void enhancedForLoop() throws Exception {
verify("EnhancedForLoop");
}

}
Loading
Loading