PsiStatement (PsiStatement commonInitializer, PsiMethod subConstructor, PsiField field, ArrayList<? super PsiElement> statementsToRemove) { final PsiCodeBlock body = subConstructor.getBody(); if (body == null) return null; final PsiStatement[] statements = body.getStatements(); // Algorithm: there should be only one write usage of field in a subConstructor, // and in that usage field must be a target of top-level assignment, and RHS of assignment // should be the same as commonInitializer if latter is non-null. // // There should be no usages before that initializer, and there should be // no write usages afterwards. PsiStatement commonInitializerCandidate = null; for (PsiStatement statement : statements) { final HashSet<PsiStatement> collectedStatements = new HashSet<>(); collectPsiStatements(statement, collectedStatements); boolean doLookup = true; for (PsiStatement collectedStatement : collectedStatements) { if (collectedStatement instanceof PsiExpressionStatement) { final PsiExpression expression = ((PsiExpressionStatement)collectedStatement).getExpression(); if (expression instanceof PsiAssignmentExpression assignmentExpression && assignmentExpression.getLExpression() instanceof PsiReferenceExpression lRef && (lRef.getQualifierExpression() == null || lRef.getQualifierExpression() instanceof PsiThisExpression) && lRef.resolve() == field) { doLookup = false; if (commonInitializerCandidate == null) { final PsiExpression initializer = assignmentExpression.getRExpression(); if (initializer == null) return null; if (commonInitializer == null) { final IsMovableInitializerVisitor visitor = new IsMovableInitializerVisitor(); statement.accept(visitor); if (visitor.isMovable()) { ChangeContextUtil.encodeContextInfo(statement, true); PsiStatement statementCopy = (PsiStatement)statement.copy(); ChangeContextUtil.clearContextInfo(statement); statementsToRemove.add(statement); commonInitializerCandidate = statementCopy; } else { return null; } } else { if (PsiEquivalenceUtil.areElementsEquivalent(commonInitializer, statement)) { statementsToRemove.add(statement); commonInitializerCandidate = commonInitializer; } else { return null; } } } else if (!PsiEquivalenceUtil.areElementsEquivalent(commonInitializerCandidate, statement)) { return null; } } } } if (doLookup) { final PsiReference[] references = ReferencesSearch.search(field, new LocalSearchScope(statement), false).toArray(PsiReference.EMPTY_ARRAY); if (commonInitializerCandidate == null && references.length > 0) { return null; } for (PsiReference reference : references) { if (RefactoringUtil.isAssignmentLHS(reference.getElement())) return null; } } } return commonInitializerCandidate; }