private static void retargetPatternVariable(@NotNull PsiExpression subExpression, @NotNull PsiPatternVariable variable) {
    List<PsiReferenceExpression> refs = VariableAccessUtils.getVariableReferences(variable);
    if (refs.isEmpty()) return;
    PsiInstanceOfExpression target = newTargetForPatternVariable(subExpression, variable);
    if (target == null) return;
    if (target.getPattern() instanceof PsiTypeTestPattern existingPattern) {
      PsiPatternVariable existingVar = existingPattern.getPatternVariable();
      if (existingVar != null) {
        for (PsiReferenceExpression ref : refs) {
          if (ref.isValid()) {
            ref.handleElementRename(existingVar.getName());
          }
        }
        return;
      }
    }
    PsiInstanceOfExpression updated = (PsiInstanceOfExpression)JavaPsiFacade.getElementFactory(subExpression.getProject())
      .createExpressionFromText("x instanceof T t", target);
    updated.getOperand().replace(target.getOperand());
    PsiTypeTestPattern newPattern = (PsiTypeTestPattern)Objects.requireNonNull(updated.getPattern());
    PsiTypeElement checkType = target.getCheckType();
    if (checkType == null) return;
    PsiPatternVariable newVariable = (PsiPatternVariable)Objects.requireNonNull(newPattern.getPatternVariable()).replace(variable);
    Objects.requireNonNull(newPattern.getCheckType()).replace(checkType);
    variable.delete();
    String name = new VariableNameGenerator(target, VariableKind.LOCAL_VARIABLE).byName(variable.getName())
      .generate(true);
    if (!name.equals(newVariable.getName())) {
      newVariable.setName(name);
      for (PsiReferenceExpression ref : refs) {
        if (ref.isValid()) {
          ref.handleElementRename(name);
        }
      }
    }
    target.replace(updated);
  }
private static void retargetPatternVariable(@NotNull PsiExpression subExpression, @NotNull PsiPatternVariable variable)