private static @Nullable PsiInstanceOfExpression newTargetForPatternVariable(@NotNull PsiExpression expression,
                                                                               @NotNull PsiPatternVariable variable) {
    if (!(variable.getPattern() instanceof PsiTypeTestPattern typeTest)) return null;
    PsiTypeElement checkType = typeTest.getCheckType();
    if (checkType == null) return null;
    if (!(typeTest.getParent() instanceof PsiInstanceOfExpression instanceOf)) return null;

    PsiTypeCastExpression cast =
      (PsiTypeCastExpression)JavaPsiFacade.getElementFactory(expression.getProject()).createExpressionFromText("(a)b", expression);
    Objects.requireNonNull(cast.getCastType()).replace(checkType);
    Objects.requireNonNull(cast.getOperand()).replace(instanceOf.getOperand());
    PsiInstanceOfExpression candidate = InstanceOfUtils.findPatternCandidate(cast, variable);
    if (candidate == null) return null;
    PsiPrimaryPattern pattern = candidate.getPattern();
    if (pattern != null) {
      if (!(pattern instanceof PsiTypeTestPattern existingTypeTest)) return null;
      PsiPatternVariable existingVar = existingTypeTest.getPatternVariable();
      if (existingVar != null && VariableAccessUtils.variableIsAssigned(existingVar)) return null;
    }
    return candidate;
  }
private static @Nullable PsiInstanceOfExpression newTargetForPatternVariable(@NotNull PsiExpression expression,
                                                                               @NotNull PsiPatternVariable variable)