diff --git a/src/main/java/org/openrewrite/staticanalysis/InlineOneTimeUsageVariable.java b/src/main/java/org/openrewrite/staticanalysis/InlineOneTimeUsageVariable.java new file mode 100644 index 000000000..fe1682610 --- /dev/null +++ b/src/main/java/org/openrewrite/staticanalysis/InlineOneTimeUsageVariable.java @@ -0,0 +1,116 @@ +/* + * Copyright 2022 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.staticanalysis; + +import org.jspecify.annotations.Nullable; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.internal.ListUtils; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.tree.Expression; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JavaType; +import org.openrewrite.java.tree.Statement; + +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import static java.util.Objects.requireNonNull; + +public class InlineOneTimeUsageVariable extends Recipe { + + @Override + public String getDisplayName() { + return "Inline local variables used only once"; + } + + @Override + public String getDescription() { + return "Inline local variables that are only used once, to reduce the code or clean up after other recipes."; + } + + @Override + public Set getTags() { + return Collections.singleton("RSPEC-S1488"); + } + + @Override + public Duration getEstimatedEffortPerOccurrence() { + return Duration.ofMinutes(2); + } + + @Override + public TreeVisitor getVisitor() { + return new JavaIsoVisitor() { + @Override + public J.Block visitBlock(J.Block block, ExecutionContext ctx) { + J.Block bl = super.visitBlock(block, ctx); + List statements = bl.getStatements(); + if (statements.size() > 1) { + String identReturned = identReturned(statements); + if (identReturned != null) { + if (statements.get(statements.size() - 2) instanceof J.VariableDeclarations) { + J.VariableDeclarations varDec = (J.VariableDeclarations) statements.get(statements.size() - 2); + J.VariableDeclarations.NamedVariable identDefinition = varDec.getVariables().get(0); + if (varDec.getLeadingAnnotations().isEmpty() && identDefinition.getSimpleName().equals(identReturned)) { + bl = bl.withStatements(ListUtils.map(statements, (i, statement) -> { + if (i == statements.size() - 2) { + return null; + } else if (i == statements.size() - 1) { + if (statement instanceof J.Return) { + J.Return return_ = (J.Return) statement; + return return_.withExpression(requireNonNull(identDefinition.getInitializer()) + .withPrefix(requireNonNull(return_.getExpression()).getPrefix())) + .withPrefix(varDec.getPrefix().withComments(ListUtils.concatAll(varDec.getComments(), return_.getComments()))); + } else if (statement instanceof J.Throw) { + J.Throw thrown = (J.Throw) statement; + return thrown.withException(requireNonNull(identDefinition.getInitializer()) + .withPrefix(requireNonNull(thrown.getException()).getPrefix())) + .withPrefix(varDec.getPrefix().withComments(ListUtils.concatAll(varDec.getComments(), thrown.getComments()))); + } + } + return statement; + })); + } + } + } + } + return bl; + } + + private @Nullable String identReturned(List stats) { + Statement lastStatement = stats.get(stats.size() - 1); + if (lastStatement instanceof J.Return) { + J.Return return_ = (J.Return) lastStatement; + Expression expression = return_.getExpression(); + if (expression instanceof J.Identifier && + !(expression.getType() instanceof JavaType.Array)) { + return ((J.Identifier) expression).getSimpleName(); + } + } else if (lastStatement instanceof J.Throw) { + J.Throw thr = (J.Throw) lastStatement; + if (thr.getException() instanceof J.Identifier) { + return ((J.Identifier) thr.getException()).getSimpleName(); + } + } + return null; + } + }; + } +} diff --git a/src/test/java/org/openrewrite/staticanalysis/InlineOneTimeUsageVariableTest.java b/src/test/java/org/openrewrite/staticanalysis/InlineOneTimeUsageVariableTest.java new file mode 100644 index 000000000..f8e45d09b --- /dev/null +++ b/src/test/java/org/openrewrite/staticanalysis/InlineOneTimeUsageVariableTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2022 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.staticanalysis; + +import org.junit.jupiter.api.Test; +import org.openrewrite.DocumentExample; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +import static org.openrewrite.java.Assertions.java; + +class InlineOneTimeUsageVariableTest implements RewriteTest { + @Override + public void defaults(RecipeSpec spec) { + spec.recipe(new InlineOneTimeUsageVariable()); + } + + @DocumentExample + @SuppressWarnings({"UnnecessaryLocalVariable", "CodeBlock2Expr", "Convert2MethodRef"}) + @Test + void inlineVariable() { + rewriteRun( + //language=java + java( + """ + class Test { + Object test() { + int y = 0; + int n = y; + return n; + } + Object test2() { + int y = 0; + int n = y; + System.out.println(n); + return n; + } + Object test3() { + String s = "0"; + String s2 = s; + return s2; + } + Object test4() { + String s = "0"; + String s2 = s; + String s3 = s2; + return s3; + } + } + """, + """ + class Test { + Object test() { + return 0; + } + Object test2() { + int n = 0; + System.out.println(n); + return n; + } + Object test3() { + return "0"; + } + Object test4() { + return "0"; + } + } + """ + ) + ); + } + +}