private static void replaceCastsWithPatternVariable(PsiIfStatement ifStatement){
    PsiInstanceOfExpression targetInstanceOf =
      PsiTreeUtil.findChildOfType(ifStatement.getCondition(), PsiInstanceOfExpression.class, false);
    if (targetInstanceOf == null) return;
    if (targetInstanceOf.getPattern() != null) return;
    PsiTypeElement type = targetInstanceOf.getCheckType();
    if (type == null) return;

    List<PsiTypeCastExpression> relatedCastExpressions = new ArrayList<>(getRelatesCastExpressions(ifStatement.getThenBranch(), targetInstanceOf));

    collectRelatedCastsFromIfCondition(ifStatement, targetInstanceOf, relatedCastExpressions);
    PsiLocalVariable castedVariable = null;
    for (PsiTypeCastExpression castExpression : relatedCastExpressions) {
      castedVariable = findCastedLocalVariable(castExpression);
      if (castedVariable != null) break;
    }

    String name = castedVariable != null
                  ? castedVariable.getName()
                  : new VariableNameGenerator(targetInstanceOf, VariableKind.LOCAL_VARIABLE).byType(type.getType()).generate(true);

    CommentTracker ct = new CommentTracker();
    for (PsiTypeCastExpression castExpression : relatedCastExpressions) {
      ct.replace(skipParenthesizedExprUp(castExpression), name);
    }
    if (castedVariable != null) {
      ct.delete(castedVariable);
    }
    ct.replaceExpressionAndRestoreComments(
      targetInstanceOf,
      ct.text(targetInstanceOf.getOperand()) + " instanceof " + ct.text(type) + " " + name
    );
  }
private static void replaceCastsWithPatternVariable(PsiIfStatement ifStatement)