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

Add a ScopedVariable trait #604

Draft
wants to merge 5 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,44 @@
/*
* 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.migrate.trait;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved

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.

Shouldn't we instead create this trait in the rewrite repo?

Cursor cursor;
Cursor scope;
J.Identifier identifier;

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

@Override
protected @Nullable ScopedVariable test(Cursor cursor) {
if (cursor.getValue() instanceof 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.

We can likely just use variable.getDeclaringScope(cursor) to obtain the variable's scope; using a trait might be overkill.

A scenario where a trait could be useful, suppose I'm at an identifier and need to determine the declaring scope of the variable that this identifier references.

void foo() {
   int x = 5;
   if (true) {
      print(x) // find the declaring scope of x at this point,
   }
}

J.VariableDeclarations.NamedVariable variable = cursor.getValue();
return new ScopedVariable(cursor, variable.getDeclaringScope(cursor), variable.getName());
Copy link
Contributor

Choose a reason for hiding this comment

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

This getDeclaringScope() utility method is probably a good starting point. But to me it looks like it misses cases like try-with-resources and exception handlers, for example. Also note that the flow scoping of instanceof patterns is quite different and probably a bad fit. Maybe worth thinking about at least.

}
return null;
}
}
}
21 changes: 21 additions & 0 deletions src/main/java/org/openrewrite/java/migrate/trait/package-info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* 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.
*/
@NullMarked
@NonNullFields
package org.openrewrite.java.migrate.trait;

import org.jspecify.annotations.NullMarked;
import org.openrewrite.internal.lang.NonNullFields;
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.migrate.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());
})
)
);
}

}