@NotNull
  @Override
  public PsiDeclarationStatement createVariableDeclarationStatement(
      @NotNull String name, @NotNull PsiType type, @Nullable PsiExpression initializer)
      throws IncorrectOperationException {
    if (!isIdentifier(name)) {
      throw new IncorrectOperationException("\"" + name + "\" is not an identifier.");
    }
    if (PsiType.NULL.equals(type)) {
      throw new IncorrectOperationException("Cannot create variable with type \"null\".");
    }

    String text = "X " + name + (initializer != null ? " = x" : "") + ";";
    PsiDeclarationStatement statement =
        (PsiDeclarationStatement) createStatementFromText(text, null);

    PsiVariable variable = (PsiVariable) statement.getDeclaredElements()[0];
    replace(variable.getTypeElement(), createTypeElement(type), text);

    boolean generateFinalLocals =
        JavaCodeStyleSettingsFacade.getInstance(myManager.getProject()).isGenerateFinalLocals();
    PsiUtil.setModifierProperty(variable, PsiModifier.FINAL, generateFinalLocals);

    if (initializer != null) {
      replace(variable.getInitializer(), initializer, text);
    }

    GeneratedMarkerVisitor.markGenerated(statement);
    return statement;
  }
 public static PsiExpression findDefinition(
     @NotNull PsiReferenceExpression referenceExpression, @Nullable PsiVariable variable) {
   if (variable == null) {
     final PsiElement target = referenceExpression.resolve();
     if (!(target instanceof PsiVariable)) {
       return null;
     }
     variable = (PsiVariable) target;
   }
   final PsiCodeBlock block = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class);
   if (block == null) {
     return null;
   }
   final PsiElement[] defs = DefUseUtil.getDefs(block, variable, referenceExpression);
   if (defs.length != 1) {
     return null;
   }
   final PsiElement def = defs[0];
   if (def instanceof PsiVariable) {
     final PsiVariable target = (PsiVariable) def;
     final PsiExpression initializer = target.getInitializer();
     return ParenthesesUtils.stripParentheses(initializer);
   } else if (def instanceof PsiReferenceExpression) {
     final PsiElement parent = def.getParent();
     if (!(parent instanceof PsiAssignmentExpression)) {
       return null;
     }
     final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) parent;
     if (assignmentExpression.getOperationTokenType() != JavaTokenType.EQ) {
       return null;
     }
     return ParenthesesUtils.stripParentheses(assignmentExpression.getRExpression());
   }
   return null;
 }
 private static boolean isIndexedListLoopStatement(PsiForStatement forStatement, boolean ignoreUntypedCollections) {
   final PsiStatement initialization = forStatement.getInitialization();
   if (!(initialization instanceof PsiDeclarationStatement)) {
     return false;
   }
   final PsiDeclarationStatement declaration = (PsiDeclarationStatement)initialization;
   final PsiElement[] declaredElements = declaration.getDeclaredElements();
   final PsiElement secondDeclaredElement;
   if (declaredElements.length == 1) {
     secondDeclaredElement = null;
   }
   else if (declaredElements.length == 2) {
     secondDeclaredElement = declaredElements[1];
   }
   else {
     return false;
   }
   final PsiElement declaredElement = declaredElements[0];
   if (!(declaredElement instanceof PsiVariable)) {
     return false;
   }
   final PsiVariable indexVariable = (PsiVariable)declaredElement;
   final PsiExpression initialValue = indexVariable.getInitializer();
   if (initialValue == null) {
     return false;
   }
   final Object constant = ExpressionUtils.computeConstantExpression(initialValue);
   if (!(constant instanceof Number)) {
     return false;
   }
   final Number number = (Number)constant;
   if (number.intValue() != 0) {
     return false;
   }
   final PsiExpression condition = forStatement.getCondition();
   final Holder collectionHolder = getCollectionFromSizeComparison(condition, indexVariable, secondDeclaredElement);
   if (collectionHolder == null) {
     return false;
   }
   final PsiStatement update = forStatement.getUpdate();
   if (!VariableAccessUtils.variableIsIncremented(indexVariable, update)) {
     return false;
   }
   final PsiStatement body = forStatement.getBody();
   if (!isIndexVariableOnlyUsedAsListIndex(collectionHolder, indexVariable, body)) {
     return false;
   }
   if (collectionHolder != Holder.DUMMY) {
     final PsiVariable collection = collectionHolder.getVariable();
     final PsiClassType collectionType = (PsiClassType)collection.getType();
     final PsiType[] parameters = collectionType.getParameters();
     if (ignoreUntypedCollections && parameters.length == 0) {
       return false;
     }
     return !VariableAccessUtils.variableIsAssigned(collection, body);
   }
   return true;
 }
 static boolean isArrayLoopStatement(PsiForStatement forStatement) {
   final PsiStatement initialization = forStatement.getInitialization();
   if (!(initialization instanceof PsiDeclarationStatement)) {
     return false;
   }
   final PsiDeclarationStatement declaration = (PsiDeclarationStatement)initialization;
   final PsiElement[] declaredElements = declaration.getDeclaredElements();
   final PsiElement secondDeclaredElement;
   if (declaredElements.length == 1) {
     secondDeclaredElement = null;
   }
   else if (declaredElements.length == 2) {
     secondDeclaredElement = declaredElements[1];
   }
   else {
     return false;
   }
   final PsiElement declaredElement = declaredElements[0];
   if (!(declaredElement instanceof PsiVariable)) {
     return false;
   }
   final PsiVariable indexVariable = (PsiVariable)declaredElement;
   final PsiExpression initialValue = indexVariable.getInitializer();
   if (initialValue == null) {
     return false;
   }
   final Object constant =
     ExpressionUtils.computeConstantExpression(initialValue);
   if (!(constant instanceof Integer)) {
     return false;
   }
   final Integer integer = (Integer)constant;
   if (integer.intValue() != 0) {
     return false;
   }
   final PsiStatement update = forStatement.getUpdate();
   if (!VariableAccessUtils.variableIsIncremented(indexVariable, update)) {
     return false;
   }
   final PsiExpression condition = forStatement.getCondition();
   final PsiReferenceExpression arrayReference = getVariableReferenceFromCondition(condition, indexVariable, secondDeclaredElement);
   if (arrayReference == null) {
     return false;
   }
   final PsiElement element = arrayReference.resolve();
   if (!(element instanceof PsiVariable)) {
     return false;
   }
   final PsiVariable arrayVariable = (PsiVariable)element;
   final PsiStatement body = forStatement.getBody();
   return body == null ||
          isIndexVariableOnlyUsedAsIndex(arrayVariable, indexVariable, body) &&
          !VariableAccessUtils.variableIsAssigned(arrayVariable, body) &&
          !VariableAccessUtils.arrayContentsAreAssigned(arrayVariable, body);
 }
  @Override
  protected void updateTitle(@Nullable PsiVariable variable, String value) {
    if (variable == null || !variable.hasInitializer()) {
      super.updateTitle(variable, value);
    } else {

      final PsiExpression initializer = variable.getInitializer();
      assert initializer != null;
      String text = variable.getText().replace(variable.getName(), value);
      text = text.replace(initializer.getText(), GosuRenderFuction.render(initializer));
      setPreviewText(text);
      revalidate();
    }
  }
 @Override
 public void visitVariable(@NotNull PsiVariable variable) {
   if (read || written) {
     return;
   }
   super.visitVariable(variable);
   final PsiExpression initalizer = variable.getInitializer();
   if (initalizer == null) {
     return;
   }
   final VariableUsedVisitor visitor = new VariableUsedVisitor(variable);
   initalizer.accept(visitor);
   read = visitor.isUsed();
   reference = visitor.getReference();
 }
Ejemplo n.º 7
0
 private Pair<PsiVariable, PsiType> findVariable(final PsiElement element) {
   PsiVariable variable = null;
   if (element instanceof PsiIdentifier) {
     if (element.getParent() instanceof PsiVariable) {
       variable = (PsiVariable) element.getParent();
     }
   } else if (element instanceof PsiJavaToken) {
     final PsiJavaToken token = (PsiJavaToken) element;
     if (token.getTokenType() != JavaTokenType.EQ) return null;
     if (token.getParent() instanceof PsiVariable) {
       variable = (PsiVariable) token.getParent();
     }
   }
   if (variable == null) {
     return null;
   }
   variableName = variable.getName();
   final PsiExpression initializer = variable.getInitializer();
   if (initializer == null) return null;
   final PsiType variableType = variable.getType();
   final PsiType initializerType = initializer.getType();
   if (!(variableType instanceof PsiClassType)) return null;
   final PsiClassType variableClassType = (PsiClassType) variableType;
   if (!variableClassType.isRaw()) return null;
   if (!(initializerType instanceof PsiClassType)) return null;
   final PsiClassType initializerClassType = (PsiClassType) initializerType;
   if (initializerClassType.isRaw()) return null;
   final PsiClassType.ClassResolveResult variableResolveResult =
       variableClassType.resolveGenerics();
   final PsiClassType.ClassResolveResult initializerResolveResult =
       initializerClassType.resolveGenerics();
   if (initializerResolveResult.getElement() == null) return null;
   final PsiSubstitutor targetSubstitutor =
       TypeConversionUtil.getClassSubstitutor(
           variableResolveResult.getElement(),
           initializerResolveResult.getElement(),
           initializerResolveResult.getSubstitutor());
   if (targetSubstitutor == null) return null;
   PsiType type =
       JavaPsiFacade.getInstance(variable.getProject())
           .getElementFactory()
           .createType(variableResolveResult.getElement(), targetSubstitutor);
   newTypeName = type.getCanonicalText();
   return Pair.create(variable, type);
 }
 private boolean isIteratorNextDeclaration(
     PsiStatement statement, String iteratorName, PsiType contentType) {
   if (!(statement instanceof PsiDeclarationStatement)) {
     return false;
   }
   final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) statement;
   final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
   if (declaredElements.length != 1) {
     return false;
   }
   final PsiElement declaredElement = declaredElements[0];
   if (!(declaredElement instanceof PsiVariable)) {
     return false;
   }
   final PsiVariable variable = (PsiVariable) declaredElement;
   final PsiExpression initializer = variable.getInitializer();
   return isIteratorNext(initializer, iteratorName, contentType);
 }
 private boolean isArrayElementDeclaration(
     PsiStatement statement, PsiVariable arrayVariable, String indexName) {
   if (!(statement instanceof PsiDeclarationStatement)) {
     return false;
   }
   final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) statement;
   final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
   if (declaredElements.length != 1) {
     return false;
   }
   final PsiElement declaredElement = declaredElements[0];
   if (!(declaredElement instanceof PsiVariable)) {
     return false;
   }
   final PsiVariable variable = (PsiVariable) declaredElement;
   final PsiExpression initializer = variable.getInitializer();
   return isArrayLookup(initializer, indexName, arrayVariable);
 }
 private boolean isListElementDeclaration(
     PsiStatement statement, PsiVariable listVariable, String indexName, PsiType type) {
   if (!(statement instanceof PsiDeclarationStatement)) {
     return false;
   }
   final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) statement;
   final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
   if (declaredElements.length != 1) {
     return false;
   }
   final PsiElement declaredElement = declaredElements[0];
   if (!(declaredElement instanceof PsiVariable)) {
     return false;
   }
   final PsiVariable variable = (PsiVariable) declaredElement;
   final PsiExpression initializer = variable.getInitializer();
   if (!isListGetLookup(initializer, indexName, listVariable)) {
     return false;
   }
   return type != null && type.equals(variable.getType());
 }
 private static PsiArrayAccessExpression getArrayAccessExpression(PsiForStatement forStatement) {
   final PsiStatement body = getBody(forStatement);
   if (body == null) {
     return null;
   }
   final PsiExpression arrayAccessExpression;
   if (body instanceof PsiExpressionStatement) {
     final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) body;
     final PsiExpression expression = expressionStatement.getExpression();
     if (!(expression instanceof PsiMethodCallExpression)) {
       return null;
     }
     final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
     final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
     PsiExpression[] expressions = argumentList.getExpressions();
     arrayAccessExpression = expressions.length == 0 ? null : expressions[0];
   } else if (body instanceof PsiDeclarationStatement) {
     final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) body;
     final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
     if (declaredElements.length != 1) {
       return null;
     }
     final PsiElement declaredElement = declaredElements[0];
     if (!(declaredElement instanceof PsiVariable)) {
       return null;
     }
     final PsiVariable variable = (PsiVariable) declaredElement;
     arrayAccessExpression = variable.getInitializer();
   } else {
     return null;
   }
   final PsiExpression deparenthesizedArgument =
       ParenthesesUtils.stripParentheses(arrayAccessExpression);
   if (!(deparenthesizedArgument instanceof PsiArrayAccessExpression)) {
     return null;
   }
   return (PsiArrayAccessExpression) deparenthesizedArgument;
 }
 private static boolean bodyIsArrayToCollectionCopy(
     PsiStatement body, PsiVariable variable, boolean shouldBeOffsetArrayAccess) {
   if (body instanceof PsiExpressionStatement) {
     final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) body;
     final PsiExpression expression = expressionStatement.getExpression();
     return expressionIsArrayToCollectionCopy(expression, variable, shouldBeOffsetArrayAccess);
   } else if (body instanceof PsiBlockStatement) {
     final PsiBlockStatement blockStatement = (PsiBlockStatement) body;
     final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
     final PsiStatement[] statements = codeBlock.getStatements();
     if (statements.length == 1) {
       return bodyIsArrayToCollectionCopy(statements[0], variable, shouldBeOffsetArrayAccess);
     } else if (statements.length == 2) {
       final PsiStatement statement = statements[0];
       if (!(statement instanceof PsiDeclarationStatement)) {
         return false;
       }
       final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) statement;
       final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
       if (declaredElements.length != 1) {
         return false;
       }
       final PsiElement declaredElement = declaredElements[0];
       if (!(declaredElement instanceof PsiVariable)) {
         return false;
       }
       final PsiVariable localVariable = (PsiVariable) declaredElement;
       final PsiExpression initializer = localVariable.getInitializer();
       if (!ExpressionUtils.isOffsetArrayAccess(initializer, variable)) {
         return false;
       }
       return bodyIsArrayToCollectionCopy(statements[1], localVariable, false);
     }
   }
   return false;
 }
  private void makeArray(PsiVariable variable) throws IncorrectOperationException {
    PsiType type = variable.getType();

    PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
    PsiType newType = type.createArrayType();

    PsiDeclarationStatement variableDeclarationStatement;
    PsiExpression initializer = variable.getInitializer();
    if (initializer == null) {
      String expression = "[1]";
      while (type instanceof PsiArrayType) {
        expression += "[1]";
        type = ((PsiArrayType) type).getComponentType();
      }
      PsiExpression init =
          factory.createExpressionFromText("new " + type.getCanonicalText() + expression, variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    } else {
      PsiExpression init =
          factory.createExpressionFromText("{ " + initializer.getText() + " }", variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    }
    PsiVariable newVariable = (PsiVariable) variableDeclarationStatement.getDeclaredElements()[0];
    PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
    PsiElement newExpression =
        factory.createExpressionFromText(variable.getName() + "[0]", variable);

    PsiElement outerCodeBlock = PsiUtil.getVariableCodeBlock(variable, null);
    if (outerCodeBlock == null) return;
    List<PsiReferenceExpression> outerReferences = new ArrayList<PsiReferenceExpression>();
    collectReferences(outerCodeBlock, variable, outerReferences);
    replaceReferences(outerReferences, newExpression);
    variable.replace(newVariable);
  }
Ejemplo n.º 14
0
 /**
  * @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 invoke(@NotNull Project project, Editor editor, PsiFile file)
      throws IncorrectOperationException {
    LOG.assertTrue(myOutOfScopeVariable != null);
    PsiManager manager = file.getManager();
    myOutOfScopeVariable.normalizeDeclaration();
    PsiUtil.setModifierProperty(myOutOfScopeVariable, PsiModifier.FINAL, false);
    PsiElement commonParent =
        PsiTreeUtil.findCommonParent(myOutOfScopeVariable, myUnresolvedReference);
    LOG.assertTrue(commonParent != null);
    PsiElement child =
        myOutOfScopeVariable.getTextRange().getStartOffset()
                < myUnresolvedReference.getTextRange().getStartOffset()
            ? myOutOfScopeVariable
            : myUnresolvedReference;

    while (child.getParent() != commonParent) child = child.getParent();
    PsiDeclarationStatement newDeclaration =
        (PsiDeclarationStatement)
            JavaPsiFacade.getInstance(manager.getProject())
                .getElementFactory()
                .createStatementFromText("int i = 0", null);
    PsiVariable variable =
        (PsiVariable) newDeclaration.getDeclaredElements()[0].replace(myOutOfScopeVariable);
    if (variable.getInitializer() != null) {
      variable.getInitializer().delete();
    }

    while (!(child instanceof PsiStatement) || !(child.getParent() instanceof PsiCodeBlock)) {
      child = child.getParent();
      commonParent = commonParent.getParent();
    }
    LOG.assertTrue(commonParent != null);
    PsiDeclarationStatement added =
        (PsiDeclarationStatement) commonParent.addBefore(newDeclaration, child);
    PsiLocalVariable addedVar = (PsiLocalVariable) added.getDeclaredElements()[0];
    manager.getCodeStyleManager().reformat(commonParent);

    // Leave initializer assignment
    PsiExpression initializer = myOutOfScopeVariable.getInitializer();
    if (initializer != null) {
      PsiExpressionStatement assignment =
          (PsiExpressionStatement)
              JavaPsiFacade.getInstance(manager.getProject())
                  .getElementFactory()
                  .createStatementFromText(myOutOfScopeVariable.getName() + "= e;", null);
      ((PsiAssignmentExpression) assignment.getExpression()).getRExpression().replace(initializer);
      assignment = (PsiExpressionStatement) manager.getCodeStyleManager().reformat(assignment);
      PsiDeclarationStatement declStatement =
          PsiTreeUtil.getParentOfType(myOutOfScopeVariable, PsiDeclarationStatement.class);
      LOG.assertTrue(declStatement != null);
      PsiElement parent = declStatement.getParent();
      if (parent instanceof PsiForStatement) {
        declStatement.replace(assignment);
      } else {
        parent.addAfter(assignment, declStatement);
      }
    }

    if (myOutOfScopeVariable.isValid()) {
      myOutOfScopeVariable.delete();
    }

    if (HighlightControlFlowUtil.checkVariableInitializedBeforeUsage(
            myUnresolvedReference,
            addedVar,
            new THashMap<PsiElement, Collection<PsiReferenceExpression>>())
        != null) {
      initialize(addedVar);
    }

    DaemonCodeAnalyzer.getInstance(project).updateVisibleHighlighters(editor);
  }
 @Nullable
 private String createListIterationText(@NotNull PsiForStatement forStatement) {
   final PsiBinaryExpression condition =
       (PsiBinaryExpression) ParenthesesUtils.stripParentheses(forStatement.getCondition());
   if (condition == null) {
     return null;
   }
   final PsiExpression lhs = ParenthesesUtils.stripParentheses(condition.getLOperand());
   if (lhs == null) {
     return null;
   }
   final PsiExpression rhs = ParenthesesUtils.stripParentheses(condition.getROperand());
   if (rhs == null) {
     return null;
   }
   final IElementType tokenType = condition.getOperationTokenType();
   final String indexName;
   PsiExpression collectionSize;
   if (JavaTokenType.LT.equals(tokenType)) {
     indexName = lhs.getText();
     collectionSize = rhs;
   } else if (JavaTokenType.GT.equals(tokenType)) {
     indexName = rhs.getText();
     collectionSize = lhs;
   } else {
     return null;
   }
   if (collectionSize instanceof PsiReferenceExpression) {
     final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) collectionSize;
     final PsiElement target = referenceExpression.resolve();
     if (target instanceof PsiVariable) {
       final PsiVariable variable = (PsiVariable) target;
       collectionSize = ParenthesesUtils.stripParentheses(variable.getInitializer());
     }
   }
   if (!(collectionSize instanceof PsiMethodCallExpression)) {
     return null;
   }
   final PsiMethodCallExpression methodCallExpression =
       (PsiMethodCallExpression) ParenthesesUtils.stripParentheses(collectionSize);
   if (methodCallExpression == null) {
     return null;
   }
   final PsiReferenceExpression listLengthExpression =
       methodCallExpression.getMethodExpression();
   final PsiExpression qualifier =
       ParenthesesUtils.stripParentheses(listLengthExpression.getQualifierExpression());
   final PsiReferenceExpression listReference;
   if (qualifier instanceof PsiReferenceExpression) {
     listReference = (PsiReferenceExpression) qualifier;
   } else {
     listReference = null;
   }
   PsiType parameterType;
   if (listReference == null) {
     parameterType = extractListTypeFromContainingClass(forStatement);
   } else {
     final PsiType type = listReference.getType();
     if (type == null) {
       return null;
     }
     parameterType = extractContentTypeFromType(type);
   }
   if (parameterType == null) {
     parameterType = TypeUtils.getObjectType(forStatement);
   }
   final String typeString = parameterType.getCanonicalText();
   final PsiVariable listVariable;
   if (listReference == null) {
     listVariable = null;
   } else {
     final PsiElement target = listReference.resolve();
     if (!(target instanceof PsiVariable)) {
       return null;
     }
     listVariable = (PsiVariable) target;
   }
   final PsiStatement body = forStatement.getBody();
   final PsiStatement firstStatement = getFirstStatement(body);
   final boolean isDeclaration =
       isListElementDeclaration(firstStatement, listVariable, indexName, parameterType);
   final String contentVariableName;
   @NonNls final String finalString;
   final PsiStatement statementToSkip;
   if (isDeclaration) {
     final PsiDeclarationStatement declarationStatement =
         (PsiDeclarationStatement) firstStatement;
     assert declarationStatement != null;
     final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
     final PsiElement declaredElement = declaredElements[0];
     if (!(declaredElement instanceof PsiVariable)) {
       return null;
     }
     final PsiVariable variable = (PsiVariable) declaredElement;
     contentVariableName = variable.getName();
     statementToSkip = declarationStatement;
     if (variable.hasModifierProperty(PsiModifier.FINAL)) {
       finalString = "final ";
     } else {
       finalString = "";
     }
   } else {
     final String collectionName;
     if (listReference == null) {
       collectionName = null;
     } else {
       collectionName = listReference.getReferenceName();
     }
     contentVariableName = createNewVariableName(forStatement, parameterType, collectionName);
     finalString = "";
     statementToSkip = null;
   }
   @NonNls final StringBuilder out = new StringBuilder();
   out.append("for(");
   out.append(finalString);
   out.append(typeString);
   out.append(' ');
   out.append(contentVariableName);
   out.append(": ");
   @NonNls final String listName;
   if (listReference == null) {
     listName = "this";
   } else {
     listName = listReference.getText();
   }
   out.append(listName);
   out.append(')');
   if (body != null) {
     replaceCollectionGetAccess(
         body, contentVariableName, listVariable, indexName, statementToSkip, out);
   }
   return out.toString();
 }
 private static boolean shouldCheckVariable(PsiVariable variable, PsiElement context) {
   return context != null
       && variable.getType().getArrayDimensions() != 0
       && !isComplexArrayExpression(variable.getInitializer());
 }
 private static void replaceConditionalWithIf(PsiConditionalExpression expression)
     throws IncorrectOperationException {
   final PsiStatement statement = PsiTreeUtil.getParentOfType(expression, PsiStatement.class);
   if (statement == null) {
     return;
   }
   final PsiVariable variable;
   if (statement instanceof PsiDeclarationStatement) {
     variable = PsiTreeUtil.getParentOfType(expression, PsiVariable.class);
   } else {
     variable = null;
   }
   final PsiExpression thenExpression = expression.getThenExpression();
   final PsiExpression elseExpression = expression.getElseExpression();
   final PsiExpression condition = expression.getCondition();
   final PsiExpression strippedCondition = ParenthesesUtils.stripParentheses(condition);
   final StringBuilder newStatement = new StringBuilder();
   newStatement.append("if(");
   if (strippedCondition != null) {
     newStatement.append(strippedCondition.getText());
   }
   newStatement.append(')');
   if (variable != null) {
     final String name = variable.getName();
     newStatement.append(name);
     newStatement.append('=');
     final PsiExpression initializer = variable.getInitializer();
     if (initializer == null) {
       return;
     }
     appendElementTextWithoutParentheses(initializer, expression, thenExpression, newStatement);
     newStatement.append("; else ");
     newStatement.append(name);
     newStatement.append('=');
     appendElementTextWithoutParentheses(initializer, expression, elseExpression, newStatement);
     newStatement.append(';');
     initializer.delete();
     final PsiManager manager = statement.getManager();
     final Project project = manager.getProject();
     final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
     final PsiElementFactory factory = facade.getElementFactory();
     final PsiStatement ifStatement =
         factory.createStatementFromText(newStatement.toString(), statement);
     final PsiElement parent = statement.getParent();
     final PsiElement addedElement = parent.addAfter(ifStatement, statement);
     final CodeStyleManager styleManager = CodeStyleManager.getInstance(manager.getProject());
     styleManager.reformat(addedElement);
   } else {
     final boolean addBraces =
         PsiTreeUtil.getParentOfType(expression, PsiIfStatement.class, true, PsiStatement.class)
             != null;
     if (addBraces || thenExpression == null) {
       newStatement.append('{');
     }
     appendElementTextWithoutParentheses(statement, expression, thenExpression, newStatement);
     if (addBraces) {
       newStatement.append("} else {");
     } else {
       if (thenExpression == null) {
         newStatement.append('}');
       }
       newStatement.append(" else ");
       if (elseExpression == null) {
         newStatement.append('{');
       }
     }
     appendElementTextWithoutParentheses(statement, expression, elseExpression, newStatement);
     if (addBraces || elseExpression == null) {
       newStatement.append('}');
     }
     replaceStatement(newStatement.toString(), statement);
   }
 }
 @Nullable
 private String createCollectionIterationText(@NotNull PsiForStatement forStatement)
     throws IncorrectOperationException {
   final PsiStatement body = forStatement.getBody();
   final PsiStatement firstStatement = getFirstStatement(body);
   final PsiStatement initialization = forStatement.getInitialization();
   if (!(initialization instanceof PsiDeclarationStatement)) {
     return null;
   }
   final PsiDeclarationStatement declaration = (PsiDeclarationStatement) initialization;
   final PsiElement declaredIterator = declaration.getDeclaredElements()[0];
   if (!(declaredIterator instanceof PsiVariable)) {
     return null;
   }
   final PsiVariable iteratorVariable = (PsiVariable) declaredIterator;
   final PsiMethodCallExpression initializer =
       (PsiMethodCallExpression) iteratorVariable.getInitializer();
   if (initializer == null) {
     return null;
   }
   final PsiType iteratorType = initializer.getType();
   if (iteratorType == null) {
     return null;
   }
   final PsiType iteratorContentType = extractContentTypeFromType(iteratorType);
   final PsiType iteratorVariableType = iteratorVariable.getType();
   final PsiType contentType;
   final PsiClassType javaLangObject = TypeUtils.getObjectType(forStatement);
   if (iteratorContentType == null) {
     final PsiType iteratorVariableContentType =
         extractContentTypeFromType(iteratorVariableType);
     if (iteratorVariableContentType == null) {
       contentType = javaLangObject;
     } else {
       contentType = iteratorVariableContentType;
     }
   } else {
     contentType = iteratorContentType;
   }
   final PsiReferenceExpression methodExpression = initializer.getMethodExpression();
   final PsiExpression collection = methodExpression.getQualifierExpression();
   final String iteratorName = iteratorVariable.getName();
   final boolean isDeclaration =
       isIteratorNextDeclaration(firstStatement, iteratorName, contentType);
   final PsiStatement statementToSkip;
   @NonNls final String finalString;
   final String contentVariableName;
   if (isDeclaration) {
     final PsiDeclarationStatement declarationStatement =
         (PsiDeclarationStatement) firstStatement;
     assert declarationStatement != null;
     final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
     final PsiElement declaredElement = declaredElements[0];
     if (!(declaredElement instanceof PsiVariable)) {
       return null;
     }
     final PsiVariable variable = (PsiVariable) declaredElement;
     contentVariableName = variable.getName();
     statementToSkip = declarationStatement;
     if (variable.hasModifierProperty(PsiModifier.FINAL)) {
       finalString = "final ";
     } else {
       finalString = "";
     }
   } else {
     if (collection instanceof PsiReferenceExpression) {
       final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) collection;
       final String collectionName = referenceExpression.getReferenceName();
       contentVariableName = createNewVariableName(forStatement, contentType, collectionName);
     } else {
       contentVariableName = createNewVariableName(forStatement, contentType, null);
     }
     final Project project = forStatement.getProject();
     final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
     if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
       finalString = "final ";
     } else {
       finalString = "";
     }
     statementToSkip = null;
   }
   final String contentTypeString = contentType.getCanonicalText();
   @NonNls final StringBuilder out = new StringBuilder();
   out.append("for(");
   out.append(finalString);
   out.append(contentTypeString);
   out.append(' ');
   out.append(contentVariableName);
   out.append(": ");
   if (!contentType.equals(javaLangObject)) {
     @NonNls final String iterableTypeString = "java.lang.Iterable<" + contentTypeString + '>';
     if (iteratorContentType == null) {
       out.append('(');
       out.append(iterableTypeString);
       out.append(')');
     }
   }
   if (collection == null) {
     out.append("this");
   } else {
     out.append(collection.getText());
   }
   out.append(')');
   replaceIteratorNext(
       body, contentVariableName, iteratorName, statementToSkip, out, contentType);
   return out.toString();
 }
 @Nullable
 private String createArrayIterationText(@NotNull PsiForStatement forStatement) {
   final PsiExpression condition = forStatement.getCondition();
   final PsiBinaryExpression strippedCondition =
       (PsiBinaryExpression) ParenthesesUtils.stripParentheses(condition);
   if (strippedCondition == null) {
     return null;
   }
   final PsiExpression lhs = ParenthesesUtils.stripParentheses(strippedCondition.getLOperand());
   if (lhs == null) {
     return null;
   }
   final PsiExpression rhs = ParenthesesUtils.stripParentheses(strippedCondition.getROperand());
   if (rhs == null) {
     return null;
   }
   final IElementType tokenType = strippedCondition.getOperationTokenType();
   final PsiReferenceExpression arrayLengthExpression;
   final String indexName;
   if (tokenType.equals(JavaTokenType.LT)) {
     arrayLengthExpression = (PsiReferenceExpression) ParenthesesUtils.stripParentheses(rhs);
     indexName = lhs.getText();
   } else if (tokenType.equals(JavaTokenType.GT)) {
     arrayLengthExpression = (PsiReferenceExpression) ParenthesesUtils.stripParentheses(lhs);
     indexName = rhs.getText();
   } else {
     return null;
   }
   if (arrayLengthExpression == null) {
     return null;
   }
   PsiReferenceExpression arrayReference =
       (PsiReferenceExpression) arrayLengthExpression.getQualifierExpression();
   if (arrayReference == null) {
     final PsiElement target = arrayLengthExpression.resolve();
     if (!(target instanceof PsiVariable)) {
       return null;
     }
     final PsiVariable variable = (PsiVariable) target;
     final PsiExpression initializer = variable.getInitializer();
     if (!(initializer instanceof PsiReferenceExpression)) {
       return null;
     }
     final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) initializer;
     arrayReference = (PsiReferenceExpression) referenceExpression.getQualifierExpression();
     if (arrayReference == null) {
       return null;
     }
   }
   final PsiType type = arrayReference.getType();
   if (!(type instanceof PsiArrayType)) {
     return null;
   }
   final PsiArrayType arrayType = (PsiArrayType) type;
   final PsiType componentType = arrayType.getComponentType();
   final String typeText = componentType.getCanonicalText();
   final PsiElement target = arrayReference.resolve();
   if (!(target instanceof PsiVariable)) {
     return null;
   }
   final PsiVariable arrayVariable = (PsiVariable) target;
   final PsiStatement body = forStatement.getBody();
   final PsiStatement firstStatement = getFirstStatement(body);
   final boolean isDeclaration =
       isArrayElementDeclaration(firstStatement, arrayVariable, indexName);
   final String contentVariableName;
   @NonNls final String finalString;
   final PsiStatement statementToSkip;
   if (isDeclaration) {
     final PsiDeclarationStatement declarationStatement =
         (PsiDeclarationStatement) firstStatement;
     assert declarationStatement != null;
     final PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
     final PsiElement declaredElement = declaredElements[0];
     if (!(declaredElement instanceof PsiVariable)) {
       return null;
     }
     final PsiVariable variable = (PsiVariable) declaredElement;
     if (VariableAccessUtils.variableIsAssigned(variable, forStatement)) {
       final String collectionName = arrayReference.getReferenceName();
       contentVariableName = createNewVariableName(forStatement, componentType, collectionName);
       final Project project = forStatement.getProject();
       final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
       if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
         finalString = "final ";
       } else {
         finalString = "";
       }
       statementToSkip = null;
     } else {
       contentVariableName = variable.getName();
       statementToSkip = declarationStatement;
       if (variable.hasModifierProperty(PsiModifier.FINAL)) {
         finalString = "final ";
       } else {
         finalString = "";
       }
     }
   } else {
     final String collectionName = arrayReference.getReferenceName();
     contentVariableName = createNewVariableName(forStatement, componentType, collectionName);
     final Project project = forStatement.getProject();
     final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
     if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
       finalString = "final ";
     } else {
       finalString = "";
     }
     statementToSkip = null;
   }
   @NonNls final StringBuilder out = new StringBuilder();
   out.append("for(");
   out.append(finalString);
   out.append(typeText);
   out.append(' ');
   out.append(contentVariableName);
   out.append(": ");
   final String arrayName = arrayReference.getText();
   out.append(arrayName);
   out.append(')');
   if (body != null) {
     replaceArrayAccess(
         body, contentVariableName, arrayVariable, indexName, statementToSkip, out);
   }
   return out.toString();
 }