PsiDeclarationStatement (@NotNull PsiVariable variable, @NotNull PsiElement location, CommentTracker tracker) { PsiStatement statement = PsiTreeUtil.getParentOfType(location, PsiStatement.class, false); assert statement != null; PsiElement statementParent = statement.getParent(); while (statementParent instanceof PsiStatement && !(statementParent instanceof PsiForStatement)) { statement = (PsiStatement)statementParent; statementParent = statement.getParent(); } assert statementParent != null; final PsiExpression initializer = variable.getInitializer(); if (isMovable(initializer) && statement instanceof PsiExpressionStatement expressionStatement) { final PsiExpression expression = expressionStatement.getExpression(); if (expression instanceof PsiAssignmentExpression assignmentExpression) { final PsiExpression rhs = assignmentExpression.getRExpression(); final PsiExpression lhs = assignmentExpression.getLExpression(); final IElementType tokenType = assignmentExpression.getOperationTokenType(); if (location.equals(lhs) && JavaTokenType.EQ == tokenType && !VariableAccessUtils.variableIsUsed(variable, rhs)) { PsiDeclarationStatement newDeclaration = createNewDeclaration(variable, rhs, tracker); newDeclaration = (PsiDeclarationStatement)statementParent.addBefore(newDeclaration, statement); final PsiElement parent = assignmentExpression.getParent(); assert parent != null; tracker.delete(parent); return newDeclaration; } } } PsiDeclarationStatement newDeclaration = createNewDeclaration(variable, initializer, tracker); if (statement instanceof PsiForStatement forStatement) { final PsiStatement initialization = forStatement.getInitialization(); newDeclaration = (PsiDeclarationStatement)forStatement.addBefore(newDeclaration, initialization); if (initialization != null) { tracker.delete(initialization); } return newDeclaration; } else { return (PsiDeclarationStatement)statementParent.addBefore(newDeclaration, statement); } }