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

InlineOneTimeUsageVariable #367

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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<String> getTags() {
return Collections.singleton("RSPEC-S1488");
}

@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(2);
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
J.Block bl = super.visitBlock(block, ctx);
List<Statement> 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<Statement> 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;
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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";
}
}
"""
)
);
}

}
Loading