@Override public boolean flip(PsiElement left, PsiElement right) { if (left instanceof PsiVariable && right instanceof PsiVariable) { final PsiElement first = left.getFirstChild(); if (!(first instanceof PsiModifierList)) { return false; } final PsiElement child = PsiTreeUtil.skipSiblingsForward(first, PsiWhiteSpace.class); if (!(child instanceof PsiTypeElement)) { return false; } final PsiElement last = child.getNextSibling(); if (!(last instanceof PsiWhiteSpace)) { return false; } final PsiElement anchor = right.getFirstChild(); if (!(anchor instanceof PsiIdentifier)) { return false; } final PsiElement semiColon = right.getLastChild(); if (!(semiColon instanceof PsiJavaToken)) { return false; } right.addRangeBefore(first, last, anchor); left.deleteChildRange(first, last); left.add(semiColon); semiColon.delete(); final PsiElement copy = left.copy(); left.replace(right); right.replace(copy); return true; } return false; }
private void changeParameter( int parameterIndex, JetParameter parameter, JetParameterInfo parameterInfo) { ASTNode valOrVarAstNode = parameter.getValOrVarNode(); PsiElement valOrVarNode = valOrVarAstNode != null ? valOrVarAstNode.getPsi() : null; JetValVar valOrVar = parameterInfo.getValOrVar(); JetPsiFactory psiFactory = JetPsiFactory(getProject()); if (valOrVarNode != null) { if (valOrVar == JetValVar.None) { valOrVarNode.delete(); } else { valOrVarNode.replace(psiFactory.createValOrVarNode(valOrVar.toString()).getPsi()); } } else if (valOrVar != JetValVar.None) { PsiElement firstChild = parameter.getFirstChild(); parameter.addBefore(psiFactory.createValOrVarNode(valOrVar.toString()).getPsi(), firstChild); parameter.addBefore(psiFactory.createWhiteSpace(), firstChild); } if (parameterInfo.getIsTypeChanged() && parameter.getTypeReference() != null) { String renderedType = parameterInfo.renderType(parameterIndex, this); parameter.setTypeReference(psiFactory.createType(renderedType)); } PsiElement identifier = parameter.getNameIdentifier(); if (identifier != null) { //noinspection unchecked String newName = parameterInfo.getInheritedName((JetFunctionDefinitionUsage<PsiElement>) this); identifier.replace(psiFactory.createIdentifier(newName)); } }
private static void swapAtComma(@NotNull PsiElement comma) { PsiElement prev = smartAdvance(comma, false); PsiElement next = smartAdvance(comma, true); if (prev != null && next != null) { if (Flipper.tryFlip(prev, next)) { return; } PsiElement copy = prev.copy(); prev.replace(next); next.replace(copy); } }
public static void replaceMovedMemberTypeParameters( final PsiElement member, final Iterable<PsiTypeParameter> parametersIterable, final PsiSubstitutor substitutor, final GroovyPsiElementFactory factory) { final Map<PsiElement, PsiElement> replacement = new LinkedHashMap<PsiElement, PsiElement>(); for (PsiTypeParameter parameter : parametersIterable) { PsiType substitutedType = substitutor.substitute(parameter); if (substitutedType == null) { substitutedType = TypeConversionUtil.erasure(factory.createType(parameter)); } PsiElement scopeElement = member instanceof GrField ? member.getParent() : member; for (PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(scopeElement))) { final PsiElement element = reference.getElement(); final PsiElement parent = element.getParent(); if (parent instanceof PsiTypeElement) { replacement.put(parent, factory.createTypeElement(substitutedType)); } else if (element instanceof GrCodeReferenceElement && substitutedType instanceof PsiClassType) { replacement.put( element, factory.createReferenceElementByType((PsiClassType) substitutedType)); } } } for (PsiElement element : replacement.keySet()) { if (element.isValid()) { element.replace(replacement.get(element)); } } }
public static PsiElement setName(@NotNull PsiElement element, @NotNull String name) throws IncorrectOperationException { PsiManager manager = element.getManager(); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); PsiIdentifier newNameIdentifier = factory.createIdentifier(name); return element.replace(newNameIdentifier); }
@Override public void replaceWithNegatedExpression(PsiElement expression) { if (expression != null && PsiTreeUtil.getParentOfType(expression, PyImportStatementBase.class, false) == null) { final PyExpression replacement = invertExpression(expression); expression.replace(replacement); } }
public static void changeModifier( PsiElement element, @Nullable JetModifierList modifierList, @Nullable PsiElement insertAnchor, JetToken[] modifiersThatCanBeReplaced, Project project, boolean toBeginning, JetModifierList listWithModifier) { PsiElement whiteSpace = JetPsiFactory.createWhiteSpace(project); if (modifierList == null) { if (listWithModifier != null) { if (insertAnchor != null) { listWithModifier = (JetModifierList) element.addBefore(listWithModifier, insertAnchor); element.addBefore(whiteSpace, insertAnchor); element.addBefore(whiteSpace, listWithModifier); } else { PsiElement firstChild = element.getFirstChild(); element.addBefore(listWithModifier, firstChild); element.addBefore(whiteSpace, firstChild); } } } else { boolean replaced = false; if (modifiersThatCanBeReplaced != null) { PsiElement toBeReplaced = null; PsiElement toReplace = null; for (JetToken modifierThatCanBeReplaced : modifiersThatCanBeReplaced) { if (modifierList.hasModifier(modifierThatCanBeReplaced)) { PsiElement modifierElement = modifierList.getModifierNode(modifierThatCanBeReplaced).getPsi(); assert modifierElement != null; if (!replaced && listWithModifier != null) { toBeReplaced = modifierElement; toReplace = listWithModifier.getFirstChild(); // modifierElement.replace(listWithModifier.getFirstChild()); replaced = true; } else { modifierList.deleteChildInternal(modifierElement.getNode()); } } } if (toBeReplaced != null && toReplace != null) { toBeReplaced.replace(toReplace); } } if (!replaced && listWithModifier != null) { if (toBeginning) { PsiElement firstChild = modifierList.getFirstChild(); modifierList.addBefore(listWithModifier.getFirstChild(), firstChild); modifierList.addBefore(whiteSpace, firstChild); } else { PsiElement lastChild = modifierList.getLastChild(); modifierList.addAfter(listWithModifier.getFirstChild(), lastChild); modifierList.addAfter(whiteSpace, lastChild); } } } }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); PsiExpression exp = expression.getElement(); if (exp == null) return; element.replace(exp); }
@Override public PsiElement handleElementRename(String s) throws IncorrectOperationException { PsiElement element = getReferenceElement(); PsiElement newIdentifier = CSharpFileFactory.createIdentifier(getProject(), s); element.replace(newIdentifier); return this; }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiExpression newExpression = factory.createExpressionFromText("new java.lang.NullPointerException()", element); element.replace(newExpression); }
protected void changeInternalUsage(InternalUsageInfo usage, PsiElementFactory factory) throws IncorrectOperationException { if (!mySettings.isChangeSignature()) return; PsiElement element = usage.getElement(); if (element instanceof PsiReferenceExpression) { PsiReferenceExpression newRef = null; if (mySettings.isMakeFieldParameters()) { PsiElement resolved = ((PsiReferenceExpression) element).resolve(); if (resolved instanceof PsiField) { String name = mySettings.getNameForField((PsiField) resolved); if (name != null) { newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null); } } } if (newRef == null && mySettings.isMakeClassParameter()) { newRef = (PsiReferenceExpression) factory.createExpressionFromText( mySettings.getClassParameterName() + "." + element.getText(), null); } if (newRef != null) { CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject); newRef = (PsiReferenceExpression) codeStyleManager.reformat(newRef); element.replace(newRef); } } else if (element instanceof PsiThisExpression && mySettings.isMakeClassParameter()) { element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null)); } else if (element instanceof PsiSuperExpression && mySettings.isMakeClassParameter()) { element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null)); } else if (element instanceof PsiNewExpression && mySettings.isMakeClassParameter()) { final PsiNewExpression newExpression = ((PsiNewExpression) element); LOG.assertTrue(newExpression.getQualifier() == null); final String newText = mySettings.getClassParameterName() + "." + newExpression.getText(); final PsiExpression expr = factory.createExpressionFromText(newText, null); element.replace(expr); } }
private static void processParameterUsage( PsiReferenceExpression ref, String oldName, String newName) throws IncorrectOperationException { PsiElement last = ref.getReferenceNameElement(); if (last instanceof PsiIdentifier && last.getText().equals(oldName)) { PsiElementFactory factory = JavaPsiFacade.getInstance(ref.getProject()).getElementFactory(); PsiIdentifier newNameIdentifier = factory.createIdentifier(newName); last.replace(newNameIdentifier); } }
@Override public void expand(@NotNull PsiElement context, @NotNull Editor editor) { PsiExpression expr = getTopmostExpression(context); PsiElement parent = expr != null ? expr.getParent() : null; if (!(parent instanceof PsiExpressionStatement)) return; PsiElementFactory factory = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory(); PsiReturnStatement returnStatement = (PsiReturnStatement) factory.createStatementFromText("return " + expr.getText() + ";", parent); parent.replace(returnStatement); }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); final String text = element.getText(); final int number = Integer.parseInt(text, 8); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiElementFactory factory = psiFacade.getElementFactory(); final PsiExpression decimalNumber = factory.createExpressionFromText(Integer.toString(number), element); element.replace(decimalNumber); }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement expression = descriptor.getPsiElement(); if (expression instanceof PyTupleExpression) { PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); PyExpressionStatement statement = elementGenerator.createFromText( LanguageLevel.forElement(expression), PyExpressionStatement.class, "(" + expression.getText() + ")"); expression.replace(statement.getExpression()); } }
private static void simplifyRedundantCast(PsiElement result) { final PsiMethodReferenceExpression methodReferenceExpression = PsiTreeUtil.findChildOfType(result, PsiMethodReferenceExpression.class); if (methodReferenceExpression != null) { final PsiElement parent = methodReferenceExpression.getParent(); if (parent instanceof PsiTypeCastExpression) { if (RedundantCastUtil.isCastRedundant((PsiTypeCastExpression) parent)) { final PsiExpression operand = ((PsiTypeCastExpression) parent).getOperand(); LOG.assertTrue(operand != null); parent.replace(operand); } } } }
private static void processMethodUsage( PsiElement ref, JavaChangeInfo changeInfo, boolean toChangeArguments, boolean toCatchExceptions, PsiMethod callee, PsiSubstitutor subsitutor, final UsageInfo[] usages) throws IncorrectOperationException { if (changeInfo.isNameChanged()) { if (ref instanceof PsiJavaCodeReferenceElement) { PsiElement last = ((PsiJavaCodeReferenceElement) ref).getReferenceNameElement(); if (last instanceof PsiIdentifier && last.getText().equals(changeInfo.getOldName())) { last.replace(changeInfo.getNewNameIdentifier()); } } } final PsiMethod caller = RefactoringUtil.getEnclosingMethod(ref); if (toChangeArguments) { final PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(ref); LOG.assertTrue(list != null); boolean toInsertDefaultValue = needDefaultValue(changeInfo, caller); if (toInsertDefaultValue && ref instanceof PsiReferenceExpression) { final PsiExpression qualifierExpression = ((PsiReferenceExpression) ref).getQualifierExpression(); if (qualifierExpression instanceof PsiSuperExpression && callerSignatureIsAboutToChangeToo(caller, usages)) { toInsertDefaultValue = false; } } fixActualArgumentsList(list, changeInfo, toInsertDefaultValue, subsitutor); } if (toCatchExceptions) { if (!(ref instanceof PsiReferenceExpression && ((PsiReferenceExpression) ref).getQualifierExpression() instanceof PsiSuperExpression)) { if (needToCatchExceptions(changeInfo, caller)) { PsiClassType[] newExceptions = callee != null ? getCalleeChangedExceptionInfo(callee) : getPrimaryChangedExceptionInfo(changeInfo); fixExceptions(ref, newExceptions); } } } }
private void addToExistingImport(PyImportElement src) { final PyElementGenerator gen = PyElementGenerator.getInstance(myTarget.getProject()); // did user choose 'import' or 'from import'? PsiElement parent = src.getParent(); if (parent instanceof PyFromImportStatement) { // add another import element right after the one we got PsiElement newImportElement = gen.createImportElement(LanguageLevel.getDefault(), myName); parent.add(newImportElement); } else { // just 'import' // all we need is to qualify our target myTarget.replace( gen.createExpressionFromText( LanguageLevel.forElement(myTarget), src.getVisibleName() + "." + myName)); } }
public PsiElement handleElementRenameSimple(String newElementName) throws IncorrectOperationException { if (!PsiUtil.isValidReferenceName(newElementName)) { final PsiElement old = getReferenceNameElement(); if (old == null) throw new IncorrectOperationException("ref has no name element"); PsiElement element = GroovyPsiElementFactory.getInstance(getProject()) .createStringLiteralForReference(newElementName); old.replace(element); return this; } return super.handleElementRenameSimple(newElementName); }
@Override public void invoke( @NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!CodeInsightUtilBase.prepareFileForWrite(startElement.getContainingFile())) { return; } PsiElement newPsi = GosuPsiParseUtil.parseIdentifierOrTokenOrRelativeType(_correctName, startElement); newPsi = findIdentifierOrToken(newPsi); PsiElement oldPsi = findIdentifierOrToken(startElement); oldPsi.replace(newPsi); }
static PsiElement replaceElementWithExpression( PsiExpression expression, PsiElementFactory factory, PsiElement element) throws IncorrectOperationException { PsiElement elementToReplace = element; PsiElement expressionToReplaceWith = expression; if (element.getParent() instanceof PsiExpressionStatement) { elementToReplace = element.getParent(); expressionToReplaceWith = factory.createStatementFromText( (expression == null ? "" : expression.getText()) + ";", null); } else if (element.getParent() instanceof PsiDeclarationStatement) { expressionToReplaceWith = factory.createStatementFromText( (expression == null ? "" : expression.getText()) + ";", null); } return elementToReplace.replace(expressionToReplaceWith); }
private void surroundWithCodeBlock(@NotNull final MoveInfo info, final boolean down) { try { final Document document = PsiDocumentManager.getInstance(statementToSurroundWithCodeBlock.getProject()) .getDocument(statementToSurroundWithCodeBlock.getContainingFile()); int startOffset = document.getLineStartOffset(info.toMove.startLine); int endOffset = getLineStartSafeOffset(document, info.toMove.endLine); if (document.getText().charAt(endOffset - 1) == '\n') endOffset--; final RangeMarker lineRangeMarker = document.createRangeMarker(startOffset, endOffset); final PsiElementFactory factory = JavaPsiFacade.getInstance(statementToSurroundWithCodeBlock.getProject()) .getElementFactory(); PsiCodeBlock codeBlock = factory.createCodeBlock(); codeBlock.add(statementToSurroundWithCodeBlock); final PsiBlockStatement blockStatement = (PsiBlockStatement) factory.createStatementFromText("{}", statementToSurroundWithCodeBlock); blockStatement.getCodeBlock().replace(codeBlock); PsiBlockStatement newStatement = (PsiBlockStatement) statementToSurroundWithCodeBlock.replace(blockStatement); newStatement = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(newStatement); info.toMove = new LineRange( document.getLineNumber(lineRangeMarker.getStartOffset()), document.getLineNumber(lineRangeMarker.getEndOffset()) + 1); PsiCodeBlock newCodeBlock = newStatement.getCodeBlock(); if (down) { PsiElement blockChild = firstNonWhiteElement(newCodeBlock.getFirstBodyElement(), true); if (blockChild == null) blockChild = newCodeBlock.getRBrace(); info.toMove2 = new LineRange( info.toMove2 .startLine, // document.getLineNumber(newCodeBlock.getParent().getTextRange().getStartOffset()), document.getLineNumber(blockChild.getTextRange().getStartOffset())); } else { int start = document.getLineNumber(newCodeBlock.getRBrace().getTextRange().getStartOffset()); int end = info.toMove.startLine; if (start > end) end = start; info.toMove2 = new LineRange(start, end); } } catch (IncorrectOperationException e) { LOG.error(e); } }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); if (element != null) { if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return; final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(element, PsiLambdaExpression.class); if (lambdaExpression != null) { final PsiElement body = lambdaExpression.getBody(); if (body != null) { PsiExpression expression = LambdaUtil.extractSingleExpressionFromBody(body); if (expression != null) { body.replace(expression); } } } } }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getStartElement(); if (element.isValid() && element instanceof GoShortVarDeclaration) { PsiElement parent = element.getParent(); if (parent instanceof GoSimpleStatement) { String left = StringUtil.join( ((GoShortVarDeclaration) element).getVarDefinitionList(), GET_TEXT_FUNCTION, ", "); String right = StringUtil.join( ((GoShortVarDeclaration) element).getExpressionList(), GET_TEXT_FUNCTION, ", "); parent.replace(GoElementFactory.createAssignmentStatement(project, left, right)); } } }
@Override public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException { PsiElement nameElement = getNameIdentifierGroovy(); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(nameElement.getProject()); PsiElement newNameElement; if (JavaPsiFacade.getInstance(getProject()).getNameHelper().isIdentifier(name)) { try { GrMethod method = factory.createMethod(name, null); newNameElement = method.getNameIdentifierGroovy(); } catch (IncorrectOperationException e) { newNameElement = factory.createLiteralFromValue(name).getFirstChild(); } } else { newNameElement = factory.createLiteralFromValue(name).getFirstChild(); } nameElement.replace(newNameElement); return this; }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { if (!FileModificationService.getInstance() .preparePsiElementForWrite(descriptor.getPsiElement())) return; final PsiElement psiElement = descriptor.getPsiElement(); if (psiElement instanceof PsiInstanceOfExpression) { try { final PsiExpression compareToNull = JavaPsiFacade.getInstance(psiElement.getProject()) .getElementFactory() .createExpressionFromText( ((PsiInstanceOfExpression) psiElement).getOperand().getText() + " != null", psiElement.getParent()); psiElement.replace(compareToNull); } catch (IncorrectOperationException e) { LOG.error(e); } } }
private void addImportStatement(ImportCandidateHolder item) { final Project project = myTarget.getProject(); final PyElementGenerator gen = PyElementGenerator.getInstance(project); AddImportHelper.ImportPriority priority = AddImportHelper.getImportPriority(myTarget, item.getFile()); PsiFile file = myTarget.getContainingFile(); InjectedLanguageManager manager = InjectedLanguageManager.getInstance(project); if (manager.isInjectedFragment(file)) { file = manager.getTopLevelFile(myTarget); } // We are trying to import top-level module or package which thus cannot be qualified if (isRoot(item.getFile())) { if (myImportLocally) { AddImportHelper.addLocalImportStatement(myTarget, myName); } else { AddImportHelper.addImportStatement(file, myName, item.getAsName(), priority, null); } } else { final QualifiedName path = item.getPath(); final String qualifiedName = path != null ? path.toString() : ""; if (myUseQualifiedImport) { String nameToImport = qualifiedName; if (item.getImportable() instanceof PsiFileSystemItem) { nameToImport += "." + myName; } if (myImportLocally) { AddImportHelper.addLocalImportStatement(myTarget, nameToImport); } else { AddImportHelper.addImportStatement(file, nameToImport, item.getAsName(), priority, null); } myTarget.replace( gen.createExpressionFromText( LanguageLevel.forElement(myTarget), qualifiedName + "." + myName)); } else { if (myImportLocally) { AddImportHelper.addLocalFromImportStatement(myTarget, qualifiedName, myName); } else { AddImportHelper.addFromImportStatement( file, qualifiedName, myName, item.getAsName(), priority, null); } } } }
@Override public void invoke( @NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { PsiReferenceExpression place = (PsiReferenceExpression) startElement; String qualifier = null; final PsiExpression qualifierExpression = place.getQualifierExpression(); if (qualifierExpression != null) { qualifier = qualifierExpression.getText(); } PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); PsiMethodCallExpression callExpression; final String call = (qualifier != null ? qualifier + "." : "") + myMethodName; if (!myIsSetter) { callExpression = (PsiMethodCallExpression) elementFactory.createExpressionFromText(call + "()", null); callExpression = (PsiMethodCallExpression) CodeStyleManager.getInstance(project).reformat(callExpression); place.replace(callExpression); } else { PsiElement parent = PsiTreeUtil.skipParentsOfType(place, PsiParenthesizedExpression.class); if (parent instanceof PsiAssignmentExpression) { final PsiExpression rExpression = ((PsiAssignmentExpression) parent).getRExpression(); final String argList = rExpression != null ? rExpression.getText() : ""; callExpression = (PsiMethodCallExpression) elementFactory.createExpressionFromText(call + "(" + argList + ")", null); callExpression = (PsiMethodCallExpression) CodeStyleManager.getInstance(project).reformat(callExpression); parent.replace(callExpression); } } }
@Override public void invoke( @NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!CodeInsightUtilBase.prepareFileForWrite(startElement.getContainingFile())) { return; } if (!(startElement instanceof GosuMethodImpl)) { return; } String src = startElement.getText(); String property = isGetter ? "property get" : "property set"; String newMethodName = methodName.substring(3); src = src.replace("function", property); src = src.replaceFirst(methodName, newMethodName); PsiElement stub = GosuPsiParseUtil.parseProgramm(src, startElement, file.getManager(), null); PsiElement newMethod = new PsiMatcherImpl(stub).descendant(hasClass(GosuMethodImpl.class)).getElement(); startElement.replace(newMethod); }
/** * @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; }