-
Notifications
You must be signed in to change notification settings - Fork 6
Issue #33: FinalLocalVariable recipe created #40
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
Merged
+731
−90
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
105 changes: 105 additions & 0 deletions
105
src/main/java/org/checkstyle/autofix/PositionHelper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
111
src/main/java/org/checkstyle/autofix/recipe/FinalLocalVariable.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
src/test/java/org/checkstyle/autofix/recipe/FinalLocalVariableTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
| } | ||
|
|
||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.