Java: cleanup

GitOrigin-RevId: 922db0ea89cc111e2a9790f1623e372cfeb71a2c
This commit is contained in:
Bas Leijdekkers
2025-08-07 16:25:03 +00:00
committed by intellij-monorepo-bot
parent 7d5bd541d5
commit 3780122878
5 changed files with 252 additions and 316 deletions
@@ -34,16 +34,16 @@ import java.util.function.Supplier;
public final class InlineMethodHandler extends JavaInlineActionHandler {
private InlineMethodHandler() {
}
private InlineMethodHandler() {}
@Override
public boolean canInlineElement(PsiElement element) {
return element instanceof PsiMethod && element.getNavigationElement() instanceof PsiMethod && element.getLanguage() == JavaLanguage.INSTANCE;
return element instanceof PsiMethod && element.getNavigationElement() instanceof PsiMethod &&
element.getLanguage() == JavaLanguage.INSTANCE;
}
@Override
public void inlineElement(final Project project, Editor editor, PsiElement element) {
public void inlineElement(Project project, Editor editor, PsiElement element) {
performInline(project, editor, (PsiMethod)element.getNavigationElement(), false);
}
@@ -69,7 +69,7 @@ public final class InlineMethodHandler extends JavaInlineActionHandler {
methodBody = specialization.get();
}
if (methodBody == null){
if (methodBody == null) {
String message;
if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
message = JavaRefactoringBundle.message("refactoring.cannot.be.applied.to.abstract.methods", getRefactoringName());
@@ -112,8 +112,8 @@ public final class InlineMethodHandler extends JavaInlineActionHandler {
return;
}
if (!isThisReference(reference)) {
String message = JavaRefactoringBundle.message("refactoring.cannot.be.applied.to.inline.non.chaining.constructors",
getRefactoringName());
String message =
JavaRefactoringBundle.message("refactoring.cannot.be.applied.to.inline.non.chaining.constructors", getRefactoringName());
CommonRefactoringUtil.showErrorHint(project, editor, message, getRefactoringName(), HelpID.INLINE_CONSTRUCTOR);
return;
}
@@ -121,7 +121,8 @@ public final class InlineMethodHandler extends JavaInlineActionHandler {
}
if (reference != null) {
final PsiElement refElement = reference.getElement();
PsiCall constructorCall = refElement instanceof PsiJavaCodeReferenceElement ? RefactoringUtil.getEnclosingConstructorCall((PsiJavaCodeReferenceElement)refElement) : null;
PsiCall constructorCall =
refElement instanceof PsiJavaCodeReferenceElement ref ? RefactoringUtil.getEnclosingConstructorCall(ref) : null;
if (constructorCall == null || !method.equals(constructorCall.resolveMethod())) reference = null;
}
}
@@ -143,8 +144,7 @@ public final class InlineMethodHandler extends JavaInlineActionHandler {
if (reference != null) {
final PsiElement referenceElement = reference.getElement();
if (referenceElement.getLanguage() == JavaLanguage.INSTANCE &&
!(referenceElement instanceof PsiJavaCodeReferenceElement)) {
if (referenceElement.getLanguage() == JavaLanguage.INSTANCE && !(referenceElement instanceof PsiJavaCodeReferenceElement)) {
reference = null;
}
}
@@ -193,16 +193,15 @@ public final class InlineMethodHandler extends JavaInlineActionHandler {
}
private static boolean checkCalls(PsiElement scope, PsiMethod method) {
if (scope instanceof PsiMethodCallExpression){
PsiMethod refMethod = (PsiMethod)((PsiMethodCallExpression)scope).getMethodExpression().resolve();
if (method.equals(refMethod)) return true;
if (scope instanceof PsiMethodCallExpression call) {
if (method.equals(call.getMethodExpression().resolve())) return true;
}
if (scope instanceof PsiMethodReferenceExpression) {
if (method.equals(((PsiMethodReferenceExpression)scope).resolve())) return true;
if (scope instanceof PsiMethodReferenceExpression ref) {
if (method.equals(ref.resolve())) return true;
}
for(PsiElement child = scope.getFirstChild(); child != null; child = child.getNextSibling()){
for (PsiElement child = scope.getFirstChild(); child != null; child = child.getNextSibling()) {
if (checkCalls(child, method)) return true;
}
@@ -59,7 +59,6 @@ import java.util.function.Function;
import java.util.function.Predicate;
import static com.intellij.openapi.util.NlsContexts.DialogMessage;
import static com.intellij.util.ObjectUtils.tryCast;
public class InlineMethodProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance(InlineMethodProcessor.class);
@@ -165,9 +164,9 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
TextOccurrencesUtil.addUsagesInStringsAndComments(myMethod, myRefactoringScope, stringToSearch, usages, infoFactory);
}
if (mySearchForTextOccurrences && myRefactoringScope instanceof GlobalSearchScope) {
if (mySearchForTextOccurrences && myRefactoringScope instanceof GlobalSearchScope scope) {
String stringToSearch = ElementDescriptionUtil.getElementDescription(myMethod, NonCodeSearchDescriptionLocation.NON_JAVA);
TextOccurrencesUtil.addTextOccurrences(myMethod, stringToSearch, (GlobalSearchScope)myRefactoringScope, usages, infoFactory);
TextOccurrencesUtil.addTextOccurrences(myMethod, stringToSearch, scope, usages, infoFactory);
}
}
@@ -240,10 +239,10 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
ContainerUtil.or(element.getReferences(), JavaLangClassMemberReference.class::isInstance)) {
conflicts.putValue(element, JavaRefactoringBundle.message("inline.method.used.in.reflection"));
}
if (element instanceof PsiMethodReferenceExpression) {
processSideEffectsInMethodReferenceQualifier(conflicts, (PsiMethodReferenceExpression)element);
if (element instanceof PsiMethodReferenceExpression ref) {
processSideEffectsInMethodReferenceQualifier(conflicts, ref);
}
if (element instanceof PsiReferenceExpression && myTransformerChooser.apply((PsiReference)element).isFallBackTransformer()) {
if (element instanceof PsiReferenceExpression ref && myTransformerChooser.apply(ref).isFallBackTransformer()) {
conflicts.putValue(element, JavaRefactoringBundle.message("inlined.method.will.be.transformed.to.single.return.form"));
}
@@ -257,8 +256,8 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
conflicts.putValue(myReference.getElement(),
JavaRefactoringBundle.message("inlined.method.will.be.transformed.to.single.return.form"));
}
else if (myReference instanceof PsiMethodReferenceExpression) {
processSideEffectsInMethodReferenceQualifier(conflicts, (PsiMethodReferenceExpression)myReference);
else if (myReference instanceof PsiMethodReferenceExpression ref) {
processSideEffectsInMethodReferenceQualifier(conflicts, ref);
}
addInaccessibleMemberConflicts(myMethod, usagesIn, new ReferencedElementsCollector(), conflicts);
addInaccessibleSuperCallsConflicts(usagesIn, conflicts);
@@ -295,7 +294,6 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
}
private void addInaccessibleSuperCallsConflicts(UsageInfo[] usagesIn, MultiMap<PsiElement, @DialogMessage String> conflicts) {
myMethod.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitClass(@NotNull PsiClass aClass) {}
@@ -320,16 +318,17 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
PsiUtil.getEnclosingStaticElement(element, targetContainingClass) != null)) {
targetContainingClasses.add(targetContainingClass);
}
else if (element instanceof PsiReferenceExpression && !ExpressionUtil.isEffectivelyUnqualified((PsiReferenceExpression)element)) {
qualifiedCall = ((PsiReferenceExpression)element).getQualifierExpression();
else if (element instanceof PsiReferenceExpression ref && !ExpressionUtil.isEffectivelyUnqualified(ref)) {
qualifiedCall = ref.getQualifierExpression();
}
}
}
final PsiMethodCallExpression methodCallExpression = PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class);
LOG.assertTrue(methodCallExpression != null);
if (!targetContainingClasses.isEmpty()) {
String descriptions = StringUtil.join(targetContainingClasses, psiClass -> RefactoringUIUtil.getDescription(psiClass, false), ",");
conflicts.putValue(expression, JavaRefactoringBundle.message("inline.method.calls.not.accessible.in", methodCallExpression.getText(), descriptions));
String names = StringUtil.join(targetContainingClasses, psiClass -> RefactoringUIUtil.getDescription(psiClass, false), ",");
String message = JavaRefactoringBundle.message("inline.method.calls.not.accessible.in", methodCallExpression.getText(), names);
conflicts.putValue(expression, message);
}
if (qualifiedCall != null) {
@@ -363,7 +362,6 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
/**
* Given a set of referencedElements, returns a map from containers (in a sense of ConflictsUtil.getContainer)
* to subsets of referencedElements that are not accessible from that container
*
*/
static Map<PsiMember, Set<PsiMember>> getInaccessible(HashSet<? extends PsiMember> referencedElements,
UsageInfo[] usages,
@@ -381,10 +379,9 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
result.put(memberContainer, inaccessibleReferenced);
for (PsiMember member : referencedElements) {
if (PsiTreeUtil.isAncestor(elementToInline, member, false)) continue;
if (elementToInline instanceof PsiClass &&
InheritanceUtil.isInheritorOrSelf((PsiClass)elementToInline, member.getContainingClass(), true)) continue;
PsiElement resolveScope = usageElement instanceof PsiReferenceExpression
? ((PsiReferenceExpression)usageElement).advancedResolve(false).getCurrentFileResolveScope()
if (elementToInline instanceof PsiClass c && InheritanceUtil.isInheritorOrSelf(c, member.getContainingClass(), true)) continue;
PsiElement resolveScope = usageElement instanceof PsiReferenceExpression ref
? ref.advancedResolve(false).getCurrentFileResolveScope()
: null;
if (!resolveHelper.isAccessible(member, member.getModifierList(), usageElement, null, resolveScope)) {
inaccessibleReferenced.add(member);
@@ -439,8 +436,8 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
GenericInlineHandler.inlineReference(new UsageInfo(myReference.getElement()), myMethod, myInliners);
}
else if (myMethod.isConstructor() && InlineUtil.isChainingConstructor(myMethod)) {
if (myReference instanceof PsiMethodReferenceExpression) {
inlineMethodReference((PsiMethodReferenceExpression)myReference);
if (myReference instanceof PsiMethodReferenceExpression ref) {
inlineMethodReference(ref);
}
else {
PsiCall constructorCall = RefactoringUtil.getEnclosingConstructorCall((PsiJavaCodeReferenceElement)myReference);
@@ -451,8 +448,8 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
}
else {
myReference = surroundWithCodeBlock(new PsiReferenceExpression[]{(PsiReferenceExpression)myReference})[0];
if (myReference instanceof PsiMethodReferenceExpression) {
inlineMethodReference((PsiMethodReferenceExpression)myReference);
if (myReference instanceof PsiMethodReferenceExpression ref) {
inlineMethodReference(ref);
}
else {
inlineMethodCall((PsiReferenceExpression)myReference);
@@ -464,17 +461,17 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
if (myMethod.isConstructor()) {
for (UsageInfo usage : usages) {
PsiElement element = usage.getElement();
if (element instanceof PsiMethodReferenceExpression) {
inlineMethodReference((PsiMethodReferenceExpression)element);
if (element instanceof PsiMethodReferenceExpression ref) {
inlineMethodReference(ref);
}
else if (element instanceof PsiJavaCodeReferenceElement) {
PsiCall constructorCall = RefactoringUtil.getEnclosingConstructorCall((PsiJavaCodeReferenceElement)element);
else if (element instanceof PsiJavaCodeReferenceElement ref) {
PsiCall constructorCall = RefactoringUtil.getEnclosingConstructorCall(ref);
if (constructorCall != null) {
inlineConstructorCall(constructorCall);
}
}
else if (element instanceof PsiEnumConstant) {
inlineConstructorCall((PsiEnumConstant) element);
else if (element instanceof PsiEnumConstant constant) {
inlineConstructorCall(constant);
}
else if (!(element instanceof PsiDocMethodOrFieldRef)) {
GenericInlineHandler.inlineReference(usage, myMethod, myInliners);
@@ -496,11 +493,11 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
continue;
}
if (element instanceof PsiReferenceExpression) {
refExprList.add((PsiReferenceExpression)element);
if (element instanceof PsiReferenceExpression ref) {
refExprList.add(ref);
}
else if (element instanceof PsiImportStaticReferenceElement) {
final JavaResolveResult[] resolveResults = ((PsiImportStaticReferenceElement)element).multiResolve(false);
else if (element instanceof PsiImportStaticReferenceElement ref) {
final JavaResolveResult[] resolveResults = ref.multiResolve(false);
if (resolveResults.length < 2) {
//no overloads available: ensure broken import are deleted and
//unused overloaded imports are deleted by optimize imports helper
@@ -514,8 +511,8 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
PsiReferenceExpression[] refs = refExprList.toArray(new PsiReferenceExpression[0]);
refs = surroundWithCodeBlock(refs);
for (PsiReferenceExpression ref : refs) {
if (ref instanceof PsiMethodReferenceExpression) {
inlineMethodReference((PsiMethodReferenceExpression)ref);
if (ref instanceof PsiMethodReferenceExpression methodRef) {
inlineMethodReference(methodRef);
}
else {
inlineMethodCall(ref);
@@ -549,11 +546,11 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
final PsiLambdaExpression lambdaExpression = LambdaRefactoringUtil.convertMethodReferenceToLambda(reference, false, false);
if (lambdaExpression == null) return;
final PsiExpression callExpression = LambdaUtil.extractSingleExpressionFromBody(lambdaExpression.getBody());
if (callExpression instanceof PsiMethodCallExpression) {
inlineMethodCall(((PsiMethodCallExpression)callExpression).getMethodExpression());
if (callExpression instanceof PsiMethodCallExpression call) {
inlineMethodCall(call.getMethodExpression());
}
else if (callExpression instanceof PsiCall) {
inlineConstructorCall((PsiCall)callExpression);
else if (callExpression instanceof PsiCall call) {
inlineConstructorCall(call);
}
else {
LOG.error("Unexpected expr: " + callExpression.getText());
@@ -591,18 +588,16 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
ChangeContextUtil.clearContextInfo(expression);
}
private static void replaceParameterReferences(final PsiElement element,
final PsiMethod oldConstructor,
final PsiExpression[] instanceCreationArguments) {
private static void replaceParameterReferences(PsiElement element, PsiMethod oldConstructor, PsiExpression[] instanceCreationArguments) {
Map<PsiReferenceExpression, PsiExpression> replacement = new LinkedHashMap<>();
element.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
super.visitReferenceExpression(expression);
PsiElement resolved = expression.resolve();
if (resolved instanceof PsiParameter &&
element.getManager().areElementsEquivalent(((PsiParameter)resolved).getDeclarationScope(), oldConstructor)) {
int parameterIndex = oldConstructor.getParameterList().getParameterIndex((PsiParameter)resolved);
if (resolved instanceof PsiParameter param &&
element.getManager().areElementsEquivalent(param.getDeclarationScope(), oldConstructor)) {
int parameterIndex = oldConstructor.getParameterList().getParameterIndex(param);
if (parameterIndex >= 0) {
replacement.put(expression, instanceCreationArguments[parameterIndex]);
}
@@ -660,23 +655,20 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
for (PsiElement e = firstAdded; e != anchor; e = e.getNextSibling()) {
style.shortenClassReferences(e);
if (e instanceof PsiDeclarationStatement) {
PsiElement[] elements = ((PsiDeclarationStatement)e).getDeclaredElements();
PsiLocalVariable var = tryCast(ArrayUtil.getFirstElement(elements), PsiLocalVariable.class);
if (var != null) {
String name = var.getName();
if (blockData.resultVar != null && name.equals(blockData.resultVar.getName())) {
resultVar = var;
}
else if (blockData.thisVar != null && name.equals(blockData.thisVar.getName())) {
thisVar = var;
}
else {
for (int i = 0; i < blockData.parmVars.length; i++) {
if (name.equals(blockData.parmVars[i].getName())) {
parmVars[i] = var;
break;
}
if (e instanceof PsiDeclarationStatement declaration &&
ArrayUtil.getFirstElement(declaration.getDeclaredElements()) instanceof PsiLocalVariable var) {
String name = var.getName();
if (blockData.resultVar != null && name.equals(blockData.resultVar.getName())) {
resultVar = var;
}
else if (blockData.thisVar != null && name.equals(blockData.thisVar.getName())) {
thisVar = var;
}
else {
for (int i = 0; i < blockData.parmVars.length; i++) {
if (name.equals(blockData.parmVars[i].getName())) {
parmVars[i] = var;
break;
}
}
}
@@ -755,11 +747,11 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
return null;
}
private void substituteMethodTypeParams(PsiElement scope, final PsiSubstitutor substitutor) {
private void substituteMethodTypeParams(PsiElement scope, PsiSubstitutor substitutor) {
InlineUtil.substituteTypeParams(scope, substitutor, myFactory);
}
private boolean syncNeeded(final PsiReferenceExpression ref) {
private boolean syncNeeded(PsiReferenceExpression ref) {
if (!myMethod.hasModifierProperty(PsiModifier.SYNCHRONIZED)) return false;
final PsiMethod containingMethod = Util.getContainingMethod(ref);
if (containingMethod == null) return true;
@@ -793,7 +785,9 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
private @Nullable PsiLocalVariable declareThis(PsiSubstitutor callSubstitutor, PsiCodeBlock block) {
PsiClass containingClass = myMethod.getContainingClass();
if (myMethod.hasModifierProperty(PsiModifier.STATIC) || containingClass == null || containingClass instanceof PsiImplicitClass) return null;
if (myMethod.hasModifierProperty(PsiModifier.STATIC) || containingClass == null || containingClass instanceof PsiImplicitClass) {
return null;
}
PsiType thisType = GenericsUtil.getVariableTypeByExpressionType(myFactory.createType(containingClass, callSubstitutor));
String thisVarName = new VariableNameGenerator(myMethod.getFirstChild(), VariableKind.LOCAL_VARIABLE)
.byType(thisType).byName("self").generate(true);
@@ -822,7 +816,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
synchronizedStatement = (PsiSynchronizedStatement)CodeStyleManager.getInstance(myProject).reformat(synchronizedStatement);
synchronizedStatement = (PsiSynchronizedStatement)block.add(synchronizedStatement);
final PsiCodeBlock synchronizedBody = Objects.requireNonNull(synchronizedStatement.getBody());
for (final PsiStatement originalStatement : originalStatements) {
for (PsiStatement originalStatement : originalStatements) {
synchronizedBody.add(originalStatement);
originalStatement.delete();
}
@@ -906,10 +900,10 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
@Override
public void visitElement(@NotNull PsiElement element) {
if (element instanceof PsiReferenceExpression) {
if (element instanceof PsiReferenceExpression ref) {
PsiReferenceExpression orig = element.getCopyableUserData(MARK_KEY);
if (orig != null) {
mapping.put(orig, (PsiReferenceExpression)element);
mapping.put(orig, ref);
}
}
super.visitElement(element);
@@ -938,18 +932,18 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
expr -> JavaPsiConstructorUtil.isConstructorCall(expr) && expr.getMethodExpression() != element)) {
return JavaRefactoringBundle.message("inline.method.multiline.method.in.ctor.call");
}
return checkUnableToInsertCodeBlock(methodBody, element,
expr -> {
PsiConditionalLoopStatement loopStatement = PsiTreeUtil.getParentOfType(expr, PsiConditionalLoopStatement.class);
return loopStatement != null && PsiTreeUtil.isAncestor(loopStatement.getCondition(), expr, false);
})
Predicate<PsiMethodCallExpression> errorCondition = call -> {
PsiConditionalLoopStatement loopStatement = PsiTreeUtil.getParentOfType(call, PsiConditionalLoopStatement.class);
return loopStatement != null && PsiTreeUtil.isAncestor(loopStatement.getCondition(), call, false);
};
return checkUnableToInsertCodeBlock(methodBody, element, errorCondition)
? JavaRefactoringBundle.message("inline.method.multiline.method.in.loop.condition")
: null;
}
private static boolean checkUnableToInsertCodeBlock(final PsiCodeBlock methodBody,
final PsiElement element,
final Predicate<? super PsiMethodCallExpression> errorCondition) {
private static boolean checkUnableToInsertCodeBlock(PsiCodeBlock methodBody,
PsiElement element,
Predicate<? super PsiMethodCallExpression> errorCondition) {
PsiStatement[] statements = methodBody.getStatements();
if (statements.length > 1 || statements.length == 1 &&
!(statements[0] instanceof PsiExpressionStatement) &&
@@ -1002,11 +996,11 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
int offset = controlFlow.getEndOffset(aReturn);
while (offset != instructions.size()) {
Instruction instruction = instructions.get(offset);
if (instruction instanceof GoToInstruction) {
offset = ((GoToInstruction)instruction).offset;
if (instruction instanceof GoToInstruction g) {
offset = g.offset;
}
else if (instruction instanceof ThrowToInstruction) {
offset = ((ThrowToInstruction)instruction).offset;
else if (instruction instanceof ThrowToInstruction t) {
offset = t.offset;
}
else if (instruction instanceof ConditionalThrowToInstruction) {
// In case of "conditional throw to", control flow will not be altered
@@ -1026,7 +1020,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
private record BlockData(PsiCodeBlock block, PsiLocalVariable thisVar, PsiLocalVariable[] parmVars, PsiLocalVariable resultVar) {}
@Override
protected @NotNull Collection<? extends PsiElement> getElementsToWrite(final @NotNull UsageViewDescriptor descriptor) {
protected @NotNull Collection<? extends PsiElement> getElementsToWrite(@NotNull UsageViewDescriptor descriptor) {
if (myInlineThisOnly) {
return Collections.singletonList(myReference.getElement());
}
@@ -29,8 +29,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.util.ObjectUtils.tryCast;
public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance(InlineToAnonymousClassProcessor.class);
@@ -42,10 +40,10 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
public InlineToAnonymousClassProcessor(Project project,
PsiClass psiClass,
final @Nullable PsiCall callToInline,
@Nullable PsiCall callToInline,
boolean inlineThisOnly,
final boolean searchInComments,
final boolean searchInNonJavaFiles) {
boolean searchInComments,
boolean searchInNonJavaFiles) {
super(project);
myClass = psiClass;
myCallToInline = callToInline;
@@ -78,9 +76,8 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
new NonCodeUsageInfoFactory(myClass, qName));
}
if (mySearchInNonJavaFiles && myRefactoringScope instanceof GlobalSearchScope) {
TextOccurrencesUtil.addTextOccurrences(myClass, qName, (GlobalSearchScope)myRefactoringScope,
nonCodeUsages, new NonCodeUsageInfoFactory(myClass, qName));
if (mySearchInNonJavaFiles && myRefactoringScope instanceof GlobalSearchScope scope) {
TextOccurrencesUtil.addTextOccurrences(myClass, qName, scope, nonCodeUsages, new NonCodeUsageInfoFactory(myClass, qName));
}
usages.addAll(nonCodeUsages);
}
@@ -105,7 +102,7 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
@Override
protected boolean isPreviewUsages(UsageInfo @NotNull [] usages) {
if (super.isPreviewUsages(usages)) return true;
for(UsageInfo usage: usages) {
for (UsageInfo usage: usages) {
if (isForcePreview(usage)) {
WindowManager.getInstance().getStatusBar(myProject).setInfo(RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files"));
return true;
@@ -114,20 +111,14 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
return false;
}
private static boolean isForcePreview(final UsageInfo usage) {
private static boolean isForcePreview(UsageInfo usage) {
if (usage.isNonCodeUsage) return true;
PsiElement element = usage.getElement();
if (element != null) {
PsiFile file = element.getContainingFile();
if (!(file instanceof PsiJavaFile)) {
return true;
}
}
return false;
return element != null && !(element.getContainingFile() instanceof PsiJavaFile);
}
@Override
protected boolean preprocessUsages(final @NotNull Ref<UsageInfo[]> refUsages) {
protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
MultiMap<PsiElement, String> conflicts = getConflicts(refUsages.get());
if (!conflicts.isEmpty()) {
return showConflicts(conflicts, refUsages.get());
@@ -135,11 +126,11 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
return super.preprocessUsages(refUsages);
}
public MultiMap<PsiElement, String> getConflicts(final UsageInfo[] usages) {
public MultiMap<PsiElement, String> getConflicts(UsageInfo[] usages) {
final MultiMap<PsiElement, String> result = new MultiMap<>();
ReferencedElementsCollector collector = new ReferencedElementsCollector() {
@Override
protected void checkAddMember(final @NotNull PsiMember member) {
protected void checkAddMember(@NotNull PsiMember member) {
if (PsiTreeUtil.isAncestor(myClass, member, false)) {
return;
}
@@ -153,7 +144,7 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
}
};
addInaccessibleMemberConflicts(usages, collector, result);
myClass.accept(new JavaRecursiveElementVisitor(){
myClass.accept(new JavaRecursiveElementVisitor() {
@Override
public void visitParameter(@NotNull PsiParameter parameter) {
super.visitParameter(parameter);
@@ -166,10 +157,9 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
if (referenceExpression != null && referenceExpression.getQualifierExpression() == refElement) {
final PsiElement resolvedMember = referenceExpression.resolve();
if (resolvedMember != null && PsiTreeUtil.isAncestor(myClass, resolvedMember, false)) {
if (resolvedMember instanceof PsiMethod) {
if (myClass.findMethodsBySignature((PsiMethod)resolvedMember, true).length > 1) { //skip inherited methods
continue;
}
if (resolvedMember instanceof PsiMethod method && myClass.findMethodsBySignature(method, true).length > 1) {
//skip inherited methods
continue;
}
result.putValue(refElement, JavaRefactoringBundle.message("inline.to.anonymous.no.method.calls"));
}
@@ -229,17 +219,16 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
LOG.assertTrue(superType != null);
List<PsiElement> elementsToDelete = new ArrayList<>();
List<PsiNewExpression> newExpressions = new ArrayList<>();
for(UsageInfo info: usages) {
for (UsageInfo info : usages) {
final PsiElement element = info.getElement();
if (element instanceof PsiNewExpression) {
newExpressions.add((PsiNewExpression)element);
if (element instanceof PsiNewExpression exp) {
newExpressions.add(exp);
}
else if (element != null && element.getParent() instanceof PsiNewExpression) {
newExpressions.add((PsiNewExpression) element.getParent());
else if (element != null && element.getParent() instanceof PsiNewExpression exp) {
newExpressions.add(exp);
}
else if (element instanceof PsiJavaCodeReferenceElement && element.getParent() instanceof PsiReferenceList refList) {
PsiClass parentClass = tryCast(refList.getParent(), PsiClass.class);
if (parentClass != null && refList == parentClass.getPermitsList()) {
if (refList.getParent() instanceof PsiClass parentClass && refList == parentClass.getPermitsList()) {
SealedUtils.removeFromPermitsList(parentClass, myClass);
}
}
@@ -255,11 +244,11 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
}
newExpressions.sort(PsiUtil.BY_POSITION);
for(PsiNewExpression newExpression: newExpressions) {
for (PsiNewExpression newExpression : newExpressions) {
replaceNewOrType(newExpression, superType);
}
for(PsiElement element: elementsToDelete) {
for (PsiElement element : elementsToDelete) {
try {
if (element.isValid()) {
element.delete();
@@ -279,7 +268,7 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
}
}
private void replaceNewOrType(final PsiNewExpression psiNewExpression, final PsiClassType superType) {
private void replaceNewOrType(PsiNewExpression psiNewExpression, PsiClassType superType) {
try {
if (!psiNewExpression.isArrayCreation()) {
new InlineToAnonymousConstructorProcessor(myClass, psiNewExpression, superType).run();
@@ -318,7 +307,7 @@ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor {
}
}
public static @Nullable PsiClassType getSuperType(final PsiClass aClass) {
public static @Nullable PsiClassType getSuperType(PsiClass aClass) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(aClass.getProject());
PsiClassType superType;
@@ -55,8 +55,7 @@ class InlineToAnonymousConstructorProcessor {
private PsiExpression[] myConstructorArguments;
private PsiParameterList myConstructorParameters;
InlineToAnonymousConstructorProcessor(final PsiClass aClass, final PsiNewExpression psiNewExpression,
final PsiType superType) {
InlineToAnonymousConstructorProcessor(PsiClass aClass, PsiNewExpression psiNewExpression, PsiType superType) {
myClass = aClass;
myNewExpression = psiNewExpression;
mySuperType = superType;
@@ -64,7 +63,7 @@ class InlineToAnonymousConstructorProcessor {
myElementFactory = JavaPsiFacade.getElementFactory(myClass.getProject());
}
public void run() throws IncorrectOperationException {
public void run() {
checkInlineChainingConstructor();
JavaResolveResult classResolveResult = myNewExpression.getClassReference().advancedResolve(false);
JavaResolveResult methodResolveResult = myNewExpression.resolveMethodGenerics();
@@ -77,13 +76,12 @@ class InlineToAnonymousConstructorProcessor {
PsiTypeParameter[] typeParams = myClass.getTypeParameters();
PsiType[] substitutedParameters = PsiType.createArray(typeParams.length);
for(int i=0; i< typeParams.length; i++) {
substitutedParameters [i] = classResolveSubstitutor.substitute(typeParams [i]);
for (int i = 0; i < typeParams.length; i++) {
substitutedParameters[i] = classResolveSubstitutor.substitute(typeParams[i]);
}
PsiNewExpression superNewExpressionTemplate = (PsiNewExpression) myElementFactory.createExpressionFromText(
"new " + substType.getCanonicalText() + "() {}",
myNewExpression.getContainingFile());
PsiNewExpression superNewExpressionTemplate = (PsiNewExpression)
myElementFactory.createExpressionFromText("new " + substType.getCanonicalText() + "() {}", myNewExpression.getContainingFile());
PsiClassInitializer initializerBlock = myElementFactory.createClassInitializer();
PsiLocalVariable outerClassLocal = null;
if (myNewExpression.getQualifier() != null && myClass.getContainingClass() != null) {
@@ -115,8 +113,8 @@ class InlineToAnonymousConstructorProcessor {
insertInitializerBefore(initializerBlock, anonymousClass, token);
}
for(PsiElement child: classCopy.getChildren()) {
if ((child instanceof PsiMethod && !((PsiMethod) child).isConstructor()) ||
for (PsiElement child : classCopy.getChildren()) {
if ((child instanceof PsiMethod method && !method.isConstructor()) ||
child instanceof PsiClassInitializer || child instanceof PsiClass) {
if (!myFieldInitializers.isEmpty() || !myLocalsForParameters.isEmpty() || classResolveSubstitutor != PsiSubstitutor.EMPTY || outerClassLocal != null) {
replaceReferences((PsiMember) child, substitutedParameters, outerClassLocal);
@@ -152,10 +150,7 @@ class InlineToAnonymousConstructorProcessor {
}
}
private static void insertInitializerBefore(final PsiClassInitializer initializerBlock,
final PsiClass anonymousClass,
final PsiElement token)
throws IncorrectOperationException {
private static void insertInitializerBefore(PsiClassInitializer initializerBlock, PsiClass anonymousClass, PsiElement token) {
anonymousClass.addBefore(CodeEditUtil.createLineFeed(token.getManager()), token);
anonymousClass.addBefore(initializerBlock, token);
anonymousClass.addBefore(CodeEditUtil.createLineFeed(token.getManager()), token);
@@ -169,10 +164,10 @@ class InlineToAnonymousConstructorProcessor {
}
}
private void analyzeConstructor(final PsiCodeBlock initializerBlock) throws IncorrectOperationException {
private void analyzeConstructor(PsiCodeBlock initializerBlock) {
PsiCodeBlock body = myConstructor.getBody();
assert body != null;
for(PsiElement child: body.getChildren()) {
for (PsiElement child : body.getChildren()) {
if (child instanceof PsiStatement stmt) {
ProcessingContext context = new ProcessingContext();
if (ourAssignmentPattern.accepts(stmt, context)) {
@@ -195,7 +190,7 @@ class InlineToAnonymousConstructorProcessor {
}
}
private boolean processAssignmentInConstructor(final PsiAssignmentExpression expression) {
private boolean processAssignmentInConstructor(PsiAssignmentExpression expression) {
if (expression.getLExpression() instanceof PsiReferenceExpression lExpr) {
final PsiExpression rExpr = expression.getRExpression();
if (rExpr == null) return false;
@@ -225,7 +220,7 @@ class InlineToAnonymousConstructorProcessor {
return false;
}
public static boolean isConstant(final PsiExpression expr) {
public static boolean isConstant(PsiExpression expr) {
Object constantValue = JavaPsiFacade.getInstance(expr.getProject()).getConstantEvaluationHelper().computeConstantExpression(expr);
return constantValue != null || ourNullPattern.accepts(expr);
}
@@ -237,7 +232,7 @@ class InlineToAnonymousConstructorProcessor {
myElementFactory.createType(outerClass), myNewExpression.getQualifier());
}
private PsiLocalVariable generateLocal(final String baseName, @NotNull PsiType type, final PsiExpression initializer) {
private PsiLocalVariable generateLocal(String baseName, @NotNull PsiType type, PsiExpression initializer) {
final Project project = myClass.getProject();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
@@ -263,10 +258,10 @@ class InlineToAnonymousConstructorProcessor {
if (parent instanceof PsiCodeBlock) {
variable = (PsiLocalVariable)((PsiDeclarationStatement)parent.addBefore(declaration, myNewStatement)).getDeclaredElements()[0];
}
else if (myNewStatement instanceof PsiLambdaExpression) {
else if (myNewStatement instanceof PsiLambdaExpression expression) {
final Object marker = new Object();
PsiTreeUtil.mark(myNewExpression, marker);
PsiCodeBlock block = CommonJavaRefactoringUtil.expandExpressionLambdaToCodeBlock((PsiLambdaExpression)myNewStatement);
PsiCodeBlock block = CommonJavaRefactoringUtil.expandExpressionLambdaToCodeBlock(expression);
myNewStatement = block.getStatements()[0];
myNewExpression = (PsiNewExpression)PsiTreeUtil.releaseMark(myNewStatement, marker);
variable = (PsiLocalVariable)((PsiDeclarationStatement)block.addBefore(declaration, myNewStatement)).getDeclaredElements()[0];
@@ -308,7 +303,7 @@ class InlineToAnonymousConstructorProcessor {
}
}
private void addSuperConstructorArguments(PsiExpressionList argumentList) throws IncorrectOperationException {
private void addSuperConstructorArguments(PsiExpressionList argumentList) {
final PsiCodeBlock body = myConstructor.getBody();
assert body != null;
PsiStatement[] statements = body.getStatements();
@@ -321,7 +316,7 @@ class InlineToAnonymousConstructorProcessor {
}
PsiExpressionList superArguments = context.get(ourCallKey).getArgumentList();
if (superArguments != null) {
for(PsiExpression argument: superArguments.getExpressions()) {
for (PsiExpression argument : superArguments.getExpressions()) {
final PsiElement superArgument = replaceParameterReferences(argument.copy(), new ArrayList<>(), true);
argumentList.add(superArgument);
}
@@ -329,8 +324,8 @@ class InlineToAnonymousConstructorProcessor {
}
private PsiElement replaceParameterReferences(PsiElement argument,
final @Nullable List<? super PsiReferenceExpression> localVarRefs,
final boolean replaceFieldsWithInitializers) throws IncorrectOperationException {
@Nullable List<? super PsiReferenceExpression> localVarRefs,
boolean replaceFieldsWithInitializers) {
if (argument instanceof PsiReferenceExpression ref && ref.resolve() instanceof PsiParameter parameter) {
if (myLocalsForParameters.containsKey(parameter)) {
return argument.replace(getParameterReference(parameter));
@@ -342,7 +337,7 @@ class InlineToAnonymousConstructorProcessor {
final List<Pair<PsiReferenceExpression, PsiParameter>> parameterReferences = new ArrayList<>();
final Map<PsiElement, PsiElement> elementsToReplace = new HashMap<>();
argument.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReferenceExpression(final @NotNull PsiReferenceExpression expression) {
@Override public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
super.visitReferenceExpression(expression);
final PsiElement psiElement = expression.resolve();
if (psiElement instanceof PsiParameter parameter && parameter.getDeclarationScope() == myConstructor) {
@@ -376,7 +371,7 @@ class InlineToAnonymousConstructorProcessor {
}
}
});
for (Pair<PsiReferenceExpression, PsiParameter> pair: parameterReferences) {
for (Pair<PsiReferenceExpression, PsiParameter> pair : parameterReferences) {
PsiReferenceExpression ref = pair.first;
PsiParameter param = pair.second;
if (myLocalsForParameters.containsKey(param)) {
@@ -395,21 +390,19 @@ class InlineToAnonymousConstructorProcessor {
return CommonJavaRefactoringUtil.replaceElementsWithMap(argument, elementsToReplace);
}
private PsiExpression getParameterReference(final PsiParameter parameter) throws IncorrectOperationException {
private PsiExpression getParameterReference(PsiParameter parameter) {
PsiLocalVariable variable = myLocalsForParameters.get(parameter);
return myElementFactory.createExpressionFromText(variable.getName(), myClass);
}
private void replaceReferences(final PsiMember method,
final PsiType[] substitutedParameters, final PsiLocalVariable outerClassLocal) throws IncorrectOperationException {
private void replaceReferences(PsiMember method, PsiType[] substitutedParameters, PsiLocalVariable outerClassLocal) {
final Map<PsiElement, PsiElement> elementsToReplace = new HashMap<>();
method.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReferenceExpression(final @NotNull PsiReferenceExpression expression) {
@Override public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
super.visitReferenceExpression(expression);
final PsiElement element = expression.resolve();
if (element instanceof PsiField) {
if (element instanceof PsiField field) {
try {
PsiField field = (PsiField)element;
if (myClass.getContainingClass() != null && field.getContainingClass() == myClass.getContainingClass() &&
outerClassLocal != null) {
PsiReferenceExpression expr = (PsiReferenceExpression)expression.copy();
@@ -424,19 +417,17 @@ class InlineToAnonymousConstructorProcessor {
}
}
@Override public void visitTypeParameter(final @NotNull PsiTypeParameter classParameter) {
@Override public void visitTypeParameter(@NotNull PsiTypeParameter classParameter) {
super.visitTypeParameter(classParameter);
PsiReferenceList list = classParameter.getExtendsList();
PsiJavaCodeReferenceElement[] referenceElements = list.getReferenceElements();
for(PsiJavaCodeReferenceElement reference: referenceElements) {
PsiElement psiElement = reference.resolve();
if (psiElement instanceof PsiTypeParameter) {
checkReplaceTypeParameter(reference, (PsiTypeParameter) psiElement);
for (PsiJavaCodeReferenceElement reference : list.getReferenceElements()) {
if (reference.resolve() instanceof PsiTypeParameter parameter) {
checkReplaceTypeParameter(reference, parameter);
}
}
}
@Override public void visitTypeElement(final @NotNull PsiTypeElement typeElement) {
@Override public void visitTypeElement(@NotNull PsiTypeElement typeElement) {
super.visitTypeElement(typeElement);
if (typeElement.getType() instanceof PsiClassType classType && classType.resolve() instanceof PsiTypeParameter typeParameter) {
checkReplaceTypeParameter(typeElement, typeParameter);
@@ -446,8 +437,8 @@ class InlineToAnonymousConstructorProcessor {
private void checkReplaceTypeParameter(PsiElement element, PsiTypeParameter target) {
PsiClass containingClass = method.getContainingClass();
PsiTypeParameter[] psiTypeParameters = containingClass.getTypeParameters();
for(int i=0; i<psiTypeParameters.length; i++) {
if (psiTypeParameters [i] == target) {
for (int i = 0; i < psiTypeParameters.length; i++) {
if (psiTypeParameters[i] == target) {
PsiType substType = substitutedParameters[i];
if (substType == null) {
substType = PsiType.getJavaLangObject(element.getManager(), ProjectScope.getAllScope(element.getProject()));