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

Introduce scoped variable trait #4682

Draft
wants to merge 3 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
Expand Up @@ -18,27 +18,43 @@
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.jspecify.annotations.Nullable;
import org.openrewrite.java.trait.ScopedVariable;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JLeftPadded;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import java.util.HashMap;
import java.util.Map;

@Value
@EqualsAndHashCode(callSuper = false)
public class ChangeFieldName<P> extends JavaIsoVisitor<P> {
String classType;
String hasName;
String toName;

Map<J.Identifier, ScopedVariable> scopedVariableMap = new HashMap<>();


@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, P p) {
new ScopedVariable.Matcher().asVisitor(var -> {
scopedVariableMap.put(var.getIdentifier(), var);
return var.getTree();
}).visit(cu, p);
return super.visitCompilationUnit(cu, p);
}

@Override
public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations.NamedVariable variable, P p) {
J.VariableDeclarations.NamedVariable v = super.visitVariable(variable, p);
J.ClassDeclaration enclosingClass = getCursor().firstEnclosing(J.ClassDeclaration.class);
if (enclosingClass == null) {
return v;
}
if (variable.isField(getCursor()) && matchesClass(enclosingClass.getType()) &&
variable.getSimpleName().equals(hasName)) {
if (scopedVariableMap.get(variable.getName()).isField(getCursor()) && matchesClass(enclosingClass.getType()) &&
variable.getSimpleName().equals(hasName)) {
if (v.getVariableType() != null) {
v = v.withVariableType(v.getVariableType().withName(toName));
}
Expand All @@ -54,7 +70,7 @@ public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations
public J.FieldAccess visitFieldAccess(J.FieldAccess fieldAccess, P p) {
J.FieldAccess f = super.visitFieldAccess(fieldAccess, p);
if (matchesClass(fieldAccess.getTarget().getType()) &&
fieldAccess.getSimpleName().equals(hasName)) {
fieldAccess.getSimpleName().equals(hasName)) {
f = f.getPadding().withName(f.getPadding().getName().withElement(f.getPadding().getName().getElement().withSimpleName(toName)));
}
return f;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@
import org.openrewrite.Cursor;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.trait.ScopedVariable;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.java.tree.TypeUtils;

import java.util.HashMap;
import java.util.Map;

import static java.util.Collections.emptyList;

public class GenerateGetterAndSetterVisitor<P> extends JavaIsoVisitor<P> {
Expand All @@ -38,9 +42,20 @@ public GenerateGetterAndSetterVisitor(String fieldName) {
this.capitalizedFieldName = StringUtils.capitalize(fieldName);
}

private Map<J.Identifier, ScopedVariable> scopedVariableMap = new HashMap<>();

@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, P p) {
new ScopedVariable.Matcher().asVisitor(var -> {
scopedVariableMap.put(var.getIdentifier(), var);
return var.getTree();
}).visit(cu, p);
return super.visitCompilationUnit(cu, p);
}

@Override
public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations.NamedVariable variable, P p) {
if (variable.isField(getCursor()) && variable.getSimpleName().equals(fieldName)) {
if (scopedVariableMap.get(variable.getName()).isField(getCursor()) && variable.getSimpleName().equals(fieldName)) {
getCursor().putMessageOnFirstEnclosing(J.ClassDeclaration.class, "varCursor", getCursor());
}
return super.visitVariable(variable, p);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.jspecify.annotations.Nullable;
import org.openrewrite.Cursor;
import org.openrewrite.Incubating;
import org.openrewrite.java.trait.ScopedVariable;
import org.openrewrite.java.tree.*;

import java.text.Normalizer;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2024 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.trait;

import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.jspecify.annotations.Nullable;
import org.openrewrite.Cursor;
import org.openrewrite.java.tree.J;
import org.openrewrite.trait.SimpleTraitMatcher;
import org.openrewrite.trait.Trait;

@Value
public class ScopedVariable implements Trait<J.VariableDeclarations.NamedVariable> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want to support instanceof pattern matching, then we won't be able to use NamedVariable as the generic type parameter but would instead have to use J for this.

Cursor cursor;
Cursor scope;
J.Identifier identifier;

public boolean isField(Cursor cursor) {
return scope.getValue() instanceof J.Block &&
scope.getParentTreeCursor().getValue() instanceof J.ClassDeclaration;
}

@RequiredArgsConstructor
public static class Matcher extends SimpleTraitMatcher<ScopedVariable> {

@Override
protected @Nullable ScopedVariable test(Cursor cursor) {
if (cursor.getValue() instanceof J.VariableDeclarations.NamedVariable) {
J.VariableDeclarations.NamedVariable variable = cursor.getValue();
return new ScopedVariable(cursor, this.getDeclaringScope(cursor), variable.getName());
}
return null;
}

private Cursor getDeclaringScope(Cursor cursor) {
return cursor.dropParentUntil(it ->
it instanceof J.Block ||
it instanceof J.Lambda ||
it instanceof J.MethodDeclaration ||
it == Cursor.ROOT_VALUE);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright 2024 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.trait;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.java.tree.J;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.openrewrite.java.Assertions.java;

class ScopedVariableTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(RewriteTest.toRecipe(() ->
new ScopedVariable.Matcher().asVisitor(a -> SearchResult.found(a.getTree(),
String.format("Identified variable %s within scope %s", a.getIdentifier(), a.getScope().getValue().getClass().getSimpleName())
)
)
));
}

@Test
@DocumentExample
void markAllFieldsInClass() {
rewriteRun(
//language=java
java(
"""
class Test {
private String field;

void doSome() {
String anotherField;
}
}
""",
"""
class Test {
private String /*~~(Identified variable field within scope Block)~~>*/field;

void doSome() {
String /*~~(Identified variable anotherField within scope Block)~~>*/anotherField;
}
}
"""
)
);
}

@Test
void markAllFieldsInMethod() {
rewriteRun(
spec -> spec.recipe(Recipe.noop()),
//language=java
java(
"""
class Test {
private String field;

void doSome() {
String anotherField;
}
}
""",
spec -> spec.beforeRecipe((source) -> {
J.MethodDeclaration md = (J.MethodDeclaration) source.getClasses().get(0).getBody().getStatements().get(1);
new ScopedVariable.Matcher().asVisitor(var -> {
assertThat(((J.Block) var.getScope().getValue())).isEqualTo(md.getBody());
return var.getTree();
}).visit(md, new InMemoryExecutionContext());
})
)
);
}

}