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

Java 10+ Local-Variable Type Inference #218

Merged
merged 24 commits into from
Jun 16, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
0bcc1cb
Add test and dummy recipe as baseline for https://github.com/openrewr…
MBoegers May 3, 2023
3c41bca
Add tests for primitives and var keywords
MBoegers May 3, 2023
862f92e
Refine and group tests as nested tests
MBoegers May 9, 2023
937ba31
Merge branch 'openrewrite:main' into 217-usage_of_var
MBoegers May 10, 2023
4bd4a60
Refine and group tests as nested tests
MBoegers May 10, 2023
8984bb5
Implement UseVarKeyword reciepe except for generics
MBoegers May 10, 2023
0180123
Add Todo to implement generics and explicitly skip them for the moment
MBoegers May 10, 2023
8926e0c
UseVarKeyword: rename variables and improve null-checking in type che…
MBoegers May 12, 2023
208fc71
Add handling of static and instance initializer blocks
MBoegers May 24, 2023
f1b73f8
add skipping of generics types
MBoegers May 24, 2023
55a3d4b
replace
MBoegers May 24, 2023
78876d8
Merge branch 'openrewrite:main' into 217-usage_of_var
MBoegers Jun 14, 2023
57ce08d
Extract handling of primitive variable definition for local variable …
MBoegers Jun 14, 2023
856dbd9
Extract handling of Object variable definition for local variable typ…
MBoegers Jun 14, 2023
0c92217
Add Recipe that combines Object and Primitive handling for var. Refac…
MBoegers Jun 14, 2023
019a7a0
add licences to source code
MBoegers Jun 14, 2023
a8d4c4f
Add DocumentedExample to tests and remove Examples from Recipe
MBoegers Jun 16, 2023
5b8f0da
simplify null handling and reorder hot paths
MBoegers Jun 16, 2023
38bb55c
Apply suggestions from code review
MBoegers Jun 16, 2023
d96566b
remove NotNull Annotaions
MBoegers Jun 16, 2023
44ee158
rework determination if inside method and add test for edgecase
MBoegers Jun 16, 2023
6c8ff8b
use configuration UseJavaVersion
MBoegers Jun 16, 2023
0a47c80
Update license header
MBoegers Jun 16, 2023
4c485cb
Merge branch 'openrewrite:main' into 217-usage_of_var
MBoegers Jun 16, 2023
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
162 changes: 162 additions & 0 deletions src/main/java/org/openrewrite/java/migrate/lang/UseVarKeyword.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/*
* Copyright 2021 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.java.migrate.lang;

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.jetbrains.annotations.NotNull;
import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.search.HasJavaVersion;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeTree;

import java.time.Duration;

import static java.lang.String.format;
import static java.util.Objects.*;

@Value
@EqualsAndHashCode(callSuper = false)
public class UseVarKeyword extends Recipe {
public String getDisplayName() {
return "Use local variable type-inference (var) where possible";
}

@Override
public String getDescription() {
return "Local variable type-inference reduce the noise produces by repeating the type definitions in Java 10 or higher.";
}

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

@Override
protected TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
return new HasJavaVersion("10", true).getVisitor();
}

@Override
protected TreeVisitor<?, ExecutionContext> getVisitor() {
// J.VariableDeclarations
return new JavaVisitor<ExecutionContext>() {
private final JavaType.Primitive SHORT_TYPE = JavaType.Primitive.Short;
private final JavaType.Primitive BYTE_TYPE = JavaType.Primitive.Byte;
private final JavaTemplate template = JavaTemplate.builder(this::getCursor, "var #{} = #{any()}")
.javaParser(JavaParser.fromJavaVersion()).build();

@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext executionContext) {
J.VariableDeclarations vd = (J.VariableDeclarations) super.visitVariableDeclarations(multiVariable, executionContext);

boolean isOutsideMethode = !determineIfIsInsideMethode(this.getCursor());
MBoegers marked this conversation as resolved.
Show resolved Hide resolved
boolean isMethodeParameter = determineIfMethodeParameter(vd, this.getCursor());
if (isOutsideMethode || isMethodeParameter) return vd;

TypeTree typeExpression = vd.getTypeExpression();
boolean isByteVariable = typeExpression instanceof J.Primitive && BYTE_TYPE.equals(typeExpression.getType());
boolean isShortVariable = typeExpression instanceof J.Primitive && SHORT_TYPE.equals(typeExpression.getType());
if (isByteVariable || isShortVariable) return vd;

boolean definesNoVariable = vd.getVariables().isEmpty();
boolean isCompoundDefinition = vd.getVariables().size() < 1;
MBoegers marked this conversation as resolved.
Show resolved Hide resolved
boolean isPureAssigment = isNull(vd.getTypeExpression());
if (definesNoVariable || isCompoundDefinition || isPureAssigment) return vd;

Expression initializer = vd.getVariables().get(0).getInitializer();
MBoegers marked this conversation as resolved.
Show resolved Hide resolved
boolean isDeclarationOnly = isNull(initializer);
boolean isNullAssigment = initializer instanceof J.Literal && isNull(((J.Literal) initializer).getValue());
boolean alreadyUseVar = typeExpression instanceof J.Identifier && "var".equals(((J.Identifier) typeExpression).getSimpleName());
boolean isGeneric = typeExpression instanceof J.ParameterizedType; // todo implement generics!
if (alreadyUseVar || isDeclarationOnly || isNullAssigment || isGeneric) return vd;

J.VariableDeclarations result = transformToVar(vd);
return result;
}

private boolean determineIfMethodeParameter(@NotNull J.VariableDeclarations vd, @NotNull Cursor cursor) {
J.MethodDeclaration methodDeclaration = cursor.firstEnclosing(J.MethodDeclaration.class);
return nonNull(methodDeclaration) && methodDeclaration.getParameters().contains(vd);
}

/**
* Determines if a cursor is contained inside a Methode declaration without an intermediate Class declaration
* @param cursor value to determine
*/
private boolean determineIfIsInsideMethode(@NotNull Cursor cursor) {
MBoegers marked this conversation as resolved.
Show resolved Hide resolved
Object current = cursor.getValue();

if (Cursor.ROOT_VALUE.equals(current)) return false; // we are at the top, no further climbing needed
if (current instanceof J.ClassDeclaration)
return false; // after a ClassDeclaration we left the scope of search
if (current instanceof J.MethodDeclaration) return true; // we found the MethodeDeclaration

return determineIfIsInsideMethode(requireNonNull(cursor.getParent())); // climb up
}

@NotNull
private J.VariableDeclarations transformToVar(@NotNull J.VariableDeclarations vd) {
Expression initializer = vd.getVariables().get(0).getInitializer();
String simpleName = vd.getVariables().get(0).getSimpleName();

if (initializer instanceof J.Literal) {
initializer = expandWithPrimitivTypeHint(vd, initializer);
}

return vd.withTemplate(template, vd.getCoordinates().replace(), simpleName, initializer);
}

@NotNull
private Expression expandWithPrimitivTypeHint(@NotNull J.VariableDeclarations vd, @NotNull Expression initializer) {
String valueSource = ((J.Literal) initializer).getValueSource();

if (isNull(valueSource)) return initializer;

boolean isLongLiteral = JavaType.Primitive.Long.equals(vd.getType());
boolean inferredAsLong = valueSource.endsWith("l") || valueSource.endsWith("L");
boolean isFloatLiteral = JavaType.Primitive.Float.equals(vd.getType());
boolean inferredAsFloat = valueSource.endsWith("f") || valueSource.endsWith("F");
boolean isDoubleLiteral = JavaType.Primitive.Double.equals(vd.getType());
boolean inferredAsDouble = valueSource.endsWith("d") || valueSource.endsWith("D") || valueSource.contains(".");

String typNotation = null;
if (isLongLiteral && !inferredAsLong) {
typNotation = "L";
} else if (isFloatLiteral && !inferredAsFloat) {
typNotation = "F";
} else if (isDoubleLiteral && !inferredAsDouble) {
typNotation = "D";
}

if (nonNull(typNotation)) {
initializer = ((J.Literal) initializer).withValueSource(format("%s%s", valueSource, typNotation));
}

return initializer;
}
};
}
}
Loading