Skip to content
Open
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,153 @@
/*
* Copyright 2025 the original author or authors.
* <p>
* Licensed under the Moderne Source Available License (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://docs.moderne.io/licensing/moderne-source-available-license
* <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.openrewrite.*;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.RenameVariable;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JLeftPadded;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Space;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.marker.Markers;

import java.util.Iterator;

import static java.util.Collections.emptyList;

public class RemovePrivateFieldUnderscores extends Recipe {

@Override
public String getDisplayName() {
return "Remove underscores from private class field names";
}

@Override
public String getDescription() {
return "Removes prefix or suffix underscores from private class field names, adding `this.` only where necessary to resolve ambiguity.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaVisitor<ExecutionContext>() {
@Override
public J visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
J.VariableDeclarations mv = (J.VariableDeclarations) super.visitVariableDeclarations(multiVariable, ctx);
if (!mv.hasModifier(J.Modifier.Type.Private)) {
return mv;
}

Cursor parent = getCursor().getParentTreeCursor();
if (!(parent.getValue() instanceof J.Block && parent.getParentTreeCursor().getValue() instanceof J.ClassDeclaration)) {
return mv;
}

for (J.VariableDeclarations.NamedVariable variable : mv.getVariables()) {
String oldName = variable.getSimpleName();
if (oldName.startsWith("_") || oldName.endsWith("_")) {
String newName = oldName.startsWith("_") ? oldName.substring(1) : oldName.substring(0, oldName.length() - 1);
if (newName.startsWith("_") || newName.endsWith("_") || newName.isEmpty()) {
continue;
}

doAfterVisit(new QualifyAmbiguousFieldAccess(variable, newName));
doAfterVisit(new RenameVariable(variable, newName));
}
}
return mv;
}
};
}

private static class QualifyAmbiguousFieldAccess extends JavaVisitor<ExecutionContext> {
private final JavaType.Variable fieldType;
private final String newFieldName;

public QualifyAmbiguousFieldAccess(J.VariableDeclarations.NamedVariable field, String newFieldName) {
this.fieldType = field.getVariableType();
this.newFieldName = newFieldName;
}

@Override
public J visitIdentifier(J.Identifier identifier, ExecutionContext ctx) {
J.Identifier id = (J.Identifier) super.visitIdentifier(identifier, ctx);
if (id.getFieldType() != null && id.getFieldType().equals(this.fieldType)) {
if (getCursor().getParentTreeCursor().getValue() instanceof J.VariableDeclarations.NamedVariable) {
return id;
}

if (getCursor().getParentTreeCursor().getValue() instanceof J.FieldAccess) {
return id;
}

if (!isAmbiguous()) {
return id;
}

return new J.FieldAccess(
Tree.randomId(),
identifier.getPrefix(),
Markers.EMPTY,
new J.Identifier(
Tree.randomId(),
Space.EMPTY,
Markers.EMPTY,
emptyList(),
"this",
identifier.getType(),
null
),
JLeftPadded.build(identifier.withPrefix(Space.EMPTY).withSimpleName(id.getSimpleName())),
identifier.getType()
);
}
return id;
}

private boolean isAmbiguous() {
Copy link
Contributor

@greg-at-moderne greg-at-moderne Sep 10, 2025

Choose a reason for hiding this comment

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

I am wondering if it wouldn't be better to re-use the existing logic of org.openrewrite.java.VariableNameUtils#generateVariableName. I'd call it with the newName as the baseName and refrain from any changes if the result is different.

This way:

  • the code is shorter here
  • and likely more thoroughly tested / better coverage of the naming logic

for (Iterator<Object> it = getCursor().getPath(); it.hasNext(); ) {
Object scope = it.next();

if (scope instanceof J.MethodDeclaration) {
for (Statement param : ((J.MethodDeclaration) scope).getParameters()) {
if (param instanceof J.VariableDeclarations) {
J.VariableDeclarations.NamedVariable namedVar = ((J.VariableDeclarations) param).getVariables().get(0);
if (namedVar.getSimpleName().equals(newFieldName)) {
return true;
}
}
}
}
else if (scope instanceof J.Block) {
for (Statement statement : ((J.Block) scope).getStatements()) {
if (statement.getId().equals(getCursor().getValue())) {
break;
}
if (statement instanceof J.VariableDeclarations) {
for (J.VariableDeclarations.NamedVariable namedVar : ((J.VariableDeclarations) statement).getVariables()) {
if (namedVar.getSimpleName().equals(newFieldName)) {
return true;
}
}
}
}
}
}
return false;
}
}
}
Loading