public static void setNewFieldVisibility(PsiField field, EncapsulateFieldsDescriptor descriptor) {
   try {
     if (descriptor.getFieldsVisibility() != null) {
       field.normalizeDeclaration();
       PsiUtil.setModifierProperty(field, descriptor.getFieldsVisibility(), true);
     }
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   }
 }
  private void doMoveField(PsiSubstitutor substitutor, MemberInfo info) {
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
    PsiField field = (PsiField) info.getMember();

    if (field instanceof HaxeVarDeclarationPart) {
      field = (HaxeVarDeclaration) field.getParent();
    }

    field.normalizeDeclaration();
    RefactoringUtil.replaceMovedMemberTypeParameters(
        field, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
    fixReferencesToStatic(field);
    if (myIsTargetInterface) {
      PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true);
    }
    final PsiMember movedElement =
        (PsiMember)
            myTargetSuperClass.addBefore(
                convertFieldToLanguage(field, myTargetSuperClass.getLanguage()),
                myTargetSuperClass.getRBrace());
    myMembersAfterMove.add(movedElement);
    field.delete();
  }
 /**
  * @param sideEffects if null, delete usages, otherwise collect side effects
  * @return true if there are at least one unrecoverable side effect found, false if no side
  *     effects, null if read usage found (may happen if interval between fix creation in invoke()
  *     call was long enough)
  * @throws com.intellij.util.IncorrectOperationException
  */
 static Boolean processUsage(
     PsiElement element, PsiVariable variable, List<PsiElement> sideEffects, int deleteMode)
     throws IncorrectOperationException {
   if (!element.isValid()) return null;
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(variable.getProject()).getElementFactory();
   while (element != null) {
     if (element instanceof PsiAssignmentExpression) {
       PsiAssignmentExpression expression = (PsiAssignmentExpression) element;
       PsiExpression lExpression = expression.getLExpression();
       // there should not be read access to the variable, otherwise it is not unused
       if (!(lExpression instanceof PsiReferenceExpression)
           || variable != ((PsiReferenceExpression) lExpression).resolve()) {
         return null;
       }
       PsiExpression rExpression = expression.getRExpression();
       rExpression = PsiUtil.deparenthesizeExpression(rExpression);
       if (rExpression == null) return true;
       // replace assignment with expression and resimplify
       boolean sideEffectFound = checkSideEffects(rExpression, variable, sideEffects);
       if (!(element.getParent() instanceof PsiExpressionStatement)
           || PsiUtil.isStatement(rExpression)) {
         if (deleteMode == MAKE_STATEMENT
             || deleteMode == DELETE_ALL
                 && !(element.getParent() instanceof PsiExpressionStatement)) {
           element = replaceElementWithExpression(rExpression, factory, element);
           while (element.getParent() instanceof PsiParenthesizedExpression) {
             element = element.getParent().replace(element);
           }
           List<PsiElement> references = new ArrayList<PsiElement>();
           collectReferences(element, variable, references);
           deleteReferences(variable, references, deleteMode);
         } else if (deleteMode == DELETE_ALL) {
           deleteWholeStatement(element, factory);
         }
         return true;
       } else {
         if (deleteMode != CANCEL) {
           deleteWholeStatement(element, factory);
         }
         return !sideEffectFound;
       }
     } else if (element instanceof PsiExpressionStatement && deleteMode != CANCEL) {
       final PsiElement parent = element.getParent();
       if (parent instanceof PsiIfStatement
           || parent instanceof PsiLoopStatement
               && ((PsiLoopStatement) parent).getBody() == element) {
         element.replace(
             JavaPsiFacade.getElementFactory(element.getProject())
                 .createStatementFromText(";", element));
       } else {
         element.delete();
       }
       break;
     } else if (element instanceof PsiVariable && element == variable) {
       PsiExpression expression = variable.getInitializer();
       if (expression != null) {
         expression = PsiUtil.deparenthesizeExpression(expression);
       }
       boolean sideEffectsFound = checkSideEffects(expression, variable, sideEffects);
       if (expression != null
           && PsiUtil.isStatement(expression)
           && variable instanceof PsiLocalVariable
           && !(variable.getParent() instanceof PsiDeclarationStatement
               && ((PsiDeclarationStatement) variable.getParent()).getDeclaredElements().length
                   > 1)) {
         if (deleteMode == MAKE_STATEMENT) {
           element = element.replace(createStatementIfNeeded(expression, factory, element));
           List<PsiElement> references = new ArrayList<PsiElement>();
           collectReferences(element, variable, references);
           deleteReferences(variable, references, deleteMode);
         } else if (deleteMode == DELETE_ALL) {
           element.delete();
         }
         return true;
       } else {
         if (deleteMode != CANCEL) {
           if (element instanceof PsiField) {
             ((PsiField) element).normalizeDeclaration();
           }
           element.delete();
         }
         return !sideEffectsFound;
       }
     }
     element = element.getParent();
   }
   return true;
 }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!myField.isValid()) return; // weird. should not get here when field becomes invalid

      final Collection<PsiReference> refs = ReferencesSearch.search(myField).findAll();
      if (refs.isEmpty()) return;
      Set<PsiReference> refsSet = new HashSet<PsiReference>(refs);
      PsiCodeBlock anchorBlock = findAnchorBlock(refs);
      if (anchorBlock == null)
        return; // was assert, but need to fix the case when obsolete inspection highlighting is
                // left
      if (!CodeInsightUtil.preparePsiElementsForWrite(anchorBlock)) return;
      final PsiElementFactory elementFactory =
          JavaPsiFacade.getInstance(project).getElementFactory();
      final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
      final String propertyName =
          styleManager.variableNameToPropertyName(myField.getName(), VariableKind.FIELD);
      String localName =
          styleManager.propertyNameToVariableName(propertyName, VariableKind.LOCAL_VARIABLE);
      localName = RefactoringUtil.suggestUniqueVariableName(localName, anchorBlock, myField);
      PsiElement firstElement = getFirstElement(refs);
      boolean mayBeFinal = mayBeFinal(refsSet, firstElement);
      PsiElement newDeclaration = null;
      try {
        final PsiElement anchor = getAnchorElement(anchorBlock, firstElement);
        if (anchor instanceof PsiExpressionStatement
            && ((PsiExpressionStatement) anchor).getExpression()
                instanceof PsiAssignmentExpression) {
          final PsiAssignmentExpression expression =
              (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression();
          if (expression.getOperationTokenType() == JavaTokenType.EQ
              && expression.getLExpression() instanceof PsiReferenceExpression
              && ((PsiReference) expression.getLExpression()).isReferenceTo(myField)) {
            final PsiExpression initializer = expression.getRExpression();
            final PsiDeclarationStatement decl =
                elementFactory.createVariableDeclarationStatement(
                    localName, myField.getType(), initializer);
            if (!mayBeFinal) {
              PsiUtil.setModifierProperty(
                  ((PsiModifierListOwner) decl.getDeclaredElements()[0]), PsiModifier.FINAL, false);
            }
            newDeclaration = anchor.replace(decl);
            refsSet.remove(expression.getLExpression());
            retargetReferences(elementFactory, localName, refsSet);
          } else {
            newDeclaration =
                addDeclarationWithFieldInitializerAndRetargetReferences(
                    elementFactory, localName, anchorBlock, anchor, refsSet);
          }
        } else {
          newDeclaration =
              addDeclarationWithFieldInitializerAndRetargetReferences(
                  elementFactory, localName, anchorBlock, anchor, refsSet);
        }
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }

      if (newDeclaration != null) {
        final PsiFile psiFile = myField.getContainingFile();
        final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null && IJSwingUtilities.hasFocus(editor.getComponent())) {
          final PsiFile file =
              PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
          if (file == psiFile) {
            editor.getCaretModel().moveToOffset(newDeclaration.getTextOffset());
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
          }
        }
      }

      try {
        myField.normalizeDeclaration();
        myField.delete();
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }