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 String buildToOffsetText(PsiExpression expression, boolean plusOne) {
   expression = ParenthesesUtils.stripParentheses(expression);
   if (expression == null) {
     return null;
   }
   if (!plusOne) {
     return expression.getText();
   }
   if (expression instanceof PsiBinaryExpression) {
     final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) expression;
     final IElementType tokenType = binaryExpression.getOperationTokenType();
     if (tokenType == JavaTokenType.MINUS) {
       final PsiExpression rhs = binaryExpression.getROperand();
       if (ExpressionUtils.isOne(rhs)) {
         return binaryExpression.getLOperand().getText();
       }
     }
   }
   final int precedence = ParenthesesUtils.getPrecedence(expression);
   if (precedence > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
     return '(' + expression.getText() + ")+1";
   } else {
     return expression.getText() + "+1";
   }
 }
예제 #3
0
 protected static void replaceExpressionWithNegatedExpression(
     @NotNull PsiExpression newExpression, @NotNull PsiExpression expression) {
   final Project project = expression.getProject();
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   PsiExpression expressionToReplace = expression;
   final String newExpressionText = newExpression.getText();
   final String expString;
   if (BoolUtils.isNegated(expression)) {
     expressionToReplace = BoolUtils.findNegation(expression);
     expString = newExpressionText;
   } else if (ComparisonUtils.isComparison(newExpression)) {
     final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) newExpression;
     final String negatedComparison =
         ComparisonUtils.getNegatedComparison(binaryExpression.getOperationTokenType());
     final PsiExpression lhs = binaryExpression.getLOperand();
     final PsiExpression rhs = binaryExpression.getROperand();
     assert rhs != null;
     expString = lhs.getText() + negatedComparison + rhs.getText();
   } else {
     if (ParenthesesUtils.getPrecedence(newExpression) > ParenthesesUtils.PREFIX_PRECEDENCE) {
       expString = "!(" + newExpressionText + ')';
     } else {
       expString = '!' + newExpressionText;
     }
   }
   final PsiExpression newCall = factory.createExpressionFromText(expString, expression);
   assert expressionToReplace != null;
   final PsiElement insertedElement = expressionToReplace.replace(newCall);
   final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
   codeStyleManager.reformat(insertedElement);
 }
 @Nullable
 private static PsiReferenceExpression getReferenceFromNullCheck(
     PsiBinaryExpression expression) {
   final PsiExpression lhs = ParenthesesUtils.stripParentheses(expression.getLOperand());
   final PsiExpression rhs = ParenthesesUtils.stripParentheses(expression.getROperand());
   if (lhs instanceof PsiReferenceExpression) {
     if (!(rhs instanceof PsiLiteralExpression && PsiType.NULL.equals(rhs.getType()))) {
       return null;
     }
     return (PsiReferenceExpression) lhs;
   } else if (rhs instanceof PsiReferenceExpression) {
     if (!(lhs instanceof PsiLiteralExpression && PsiType.NULL.equals(lhs.getType()))) {
       return null;
     }
     return (PsiReferenceExpression) rhs;
   } else {
     return null;
   }
 }
 static boolean isComplexArrayExpression(PsiExpression expression) {
   expression = ParenthesesUtils.stripParentheses(expression);
   if (expression == null) {
     return false;
   }
   if (expression instanceof PsiNewExpression) {
     final PsiNewExpression newExpression = (PsiNewExpression) expression;
     final PsiArrayInitializerExpression arrayInitializer = newExpression.getArrayInitializer();
     return isComplexArrayExpression(arrayInitializer);
   } else if (expression instanceof PsiArrayInitializerExpression) {
     final PsiArrayInitializerExpression arrayInitializerExpression =
         (PsiArrayInitializerExpression) expression;
     for (PsiExpression initializer : arrayInitializerExpression.getInitializers()) {
       if (isComplexArrayExpression(initializer)) {
         return true;
       }
     }
     return false;
   } else if (expression instanceof PsiReferenceExpression) {
     return expression.getType() instanceof PsiArrayType;
   } else if (expression instanceof PsiArrayAccessExpression) {
     return true;
   } else if (expression instanceof PsiTypeCastExpression) {
     final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) expression;
     return isComplexArrayExpression(typeCastExpression.getOperand());
   } else if (expression instanceof PsiConditionalExpression) {
     final PsiConditionalExpression conditionalExpression =
         (PsiConditionalExpression) expression;
     return isComplexArrayExpression(conditionalExpression.getThenExpression())
         || isComplexArrayExpression(conditionalExpression.getElseExpression());
   } else if (expression instanceof PsiMethodCallExpression) {
     final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
     final PsiMethod method = methodCallExpression.resolveMethod();
     if (method == null) {
       return true;
     }
     if (CloneUtils.isClone(method)) {
       return false;
     }
     @NonNls final String name = method.getName();
     if ("copyOf".equals(name) || "copyOfRange".equals(name)) {
       final PsiClass aClass = method.getContainingClass();
       if (aClass != null
           && CommonClassNames.JAVA_UTIL_ARRAYS.equals(aClass.getQualifiedName())) {
         return false;
       }
     } else if ("toArray".equals(name)
         && InheritanceUtil.isInheritor(method.getContainingClass(), "java.util.Collection")) {
       return false;
     }
     return true;
   }
   return true;
 }
 @Override
 public void visitThrowStatement(PsiThrowStatement statement) {
   super.visitThrowStatement(statement);
   final PsiExpression exception = ParenthesesUtils.stripParentheses(statement.getException());
   if (!(exception instanceof PsiLiteralExpression)) {
     return;
   }
   final PsiType type = exception.getType();
   if (!PsiType.NULL.equals(type)) {
     return;
   }
   registerError(exception);
 }
    private boolean isListGetLookup(PsiElement element,
                                    String indexName,
                                    PsiVariable listVariable) {
      if (!(element instanceof PsiExpression)) {
        return false;
      }
      final PsiExpression expression = (PsiExpression)element;
      if (!expressionIsListGetLookup(expression)) {
        return false;
      }
      final PsiMethodCallExpression methodCallExpression =
        (PsiMethodCallExpression)
          ParenthesesUtils.stripParentheses(expression);
      if (methodCallExpression == null) {
        return false;
      }
      final PsiReferenceExpression methodExpression =
        methodCallExpression.getMethodExpression();
      final PsiExpression qualifierExpression =
        methodExpression.getQualifierExpression();

      final PsiExpressionList argumentList =
        methodCallExpression.getArgumentList();
      final PsiExpression[] expressions = argumentList.getExpressions();
      if (expressions.length != 1) {
        return false;
      }
      if (!indexName.equals(expressions[0].getText())) {
        return false;
      }
      if (qualifierExpression == null ||
          qualifierExpression instanceof PsiThisExpression ||
          qualifierExpression instanceof PsiSuperExpression) {
        return listVariable == null;
      }
      if (!(qualifierExpression instanceof PsiReferenceExpression)) {
        return false;
      }
      final PsiReferenceExpression referenceExpression =
        (PsiReferenceExpression)qualifierExpression;
      final PsiExpression qualifier =
        referenceExpression.getQualifierExpression();
      if (qualifier != null && !(qualifier instanceof PsiThisExpression) &&
          !(qualifier instanceof PsiSuperExpression)) {
        return false;
      }
      final PsiElement target = referenceExpression.resolve();
      return listVariable.equals(target);
    }
 private static boolean expressionIsArrayToCollectionCopy(
     PsiExpression expression, PsiVariable variable, boolean shouldBeOffsetArrayAccess) {
   expression = ParenthesesUtils.stripParentheses(expression);
   if (expression == null) {
     return false;
   }
   if (!(expression instanceof PsiMethodCallExpression)) {
     return false;
   }
   final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
   final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length != 1) {
     return false;
   }
   final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
   final PsiExpression qualifier = methodExpression.getQualifierExpression();
   if (!(qualifier instanceof PsiReferenceExpression)
       && !(qualifier instanceof PsiThisExpression)
       && !(qualifier instanceof PsiSuperExpression)) {
     return false;
   }
   final PsiExpression argument = arguments[0];
   final PsiType argumentType = argument.getType();
   if (argumentType instanceof PsiPrimitiveType) {
     return false;
   }
   if (SideEffectChecker.mayHaveSideEffects(argument)) {
     return false;
   }
   if (shouldBeOffsetArrayAccess) {
     if (!ExpressionUtils.isOffsetArrayAccess(argument, variable)) {
       return false;
     }
   } else if (!VariableAccessUtils.evaluatesToVariable(argument, variable)) {
     return false;
   }
   final PsiMethod method = methodCallExpression.resolveMethod();
   if (method == null) {
     return false;
   }
   @NonNls final String name = method.getName();
   if (!name.equals("add")) {
     return false;
   }
   final PsiClass containingClass = method.getContainingClass();
   return InheritanceUtil.isInheritor(containingClass, CommonClassNames.JAVA_UTIL_COLLECTION);
 }
 private static void appendElementTextWithoutParentheses(
     @NotNull PsiElement element,
     @NotNull PsiElement elementToReplace,
     @Nullable PsiExpression replacementExpression,
     @NotNull StringBuilder out) {
   final PsiElement expressionParent = elementToReplace.getParent();
   if (expressionParent instanceof PsiParenthesizedExpression) {
     final PsiElement grandParent = expressionParent.getParent();
     if (replacementExpression == null
         || !(grandParent instanceof PsiExpression)
         || !ParenthesesUtils.areParenthesesNeeded(
             replacementExpression, (PsiExpression) grandParent, false)) {
       appendElementText(element, expressionParent, replacementExpression, out);
       return;
     }
   }
   appendElementText(element, elementToReplace, replacementExpression, out);
 }
 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;
 }
 @Nullable
 private static PsiReferenceExpression getReferenceFromInstanceofExpression(
     PsiExpression expression) {
   if (expression instanceof PsiParenthesizedExpression) {
     final PsiParenthesizedExpression parenthesizedExpression =
         (PsiParenthesizedExpression) expression;
     return getReferenceFromInstanceofExpression(parenthesizedExpression.getExpression());
   } else if (expression instanceof PsiInstanceOfExpression) {
     final PsiInstanceOfExpression instanceOfExpression = (PsiInstanceOfExpression) expression;
     final PsiExpression operand =
         ParenthesesUtils.stripParentheses(instanceOfExpression.getOperand());
     if (!(operand instanceof PsiReferenceExpression)) {
       return null;
     }
     return (PsiReferenceExpression) operand;
   } else if (expression instanceof PsiPolyadicExpression) {
     final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) expression;
     final IElementType tokenType = polyadicExpression.getOperationTokenType();
     if (JavaTokenType.OROR != tokenType) {
       return null;
     }
     final PsiExpression[] operands = polyadicExpression.getOperands();
     final PsiReferenceExpression referenceExpression =
         getReferenceFromInstanceofExpression(operands[0]);
     if (referenceExpression == null) {
       return null;
     }
     for (int i = 1, operandsLength = operands.length; i < operandsLength; i++) {
       if (!referencesEqual(
           referenceExpression, getReferenceFromInstanceofExpression(operands[i]))) {
         return null;
       }
     }
     return referenceExpression;
   } else {
     return null;
   }
 }
 @Nullable
 private static String buildFromOffsetText(PsiExpression expression, PsiLocalVariable variable)
     throws IncorrectOperationException {
   expression = ParenthesesUtils.stripParentheses(expression);
   if (expression == null) {
     return null;
   }
   final String expressionText = expression.getText();
   final String variableName = variable.getName();
   if (expressionText.equals(variableName)) {
     final PsiExpression initialValue = variable.getInitializer();
     if (initialValue == null) {
       return null;
     }
     return initialValue.getText();
   }
   if (expression instanceof PsiBinaryExpression) {
     final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) expression;
     final PsiExpression lhs = binaryExpression.getLOperand();
     final PsiExpression rhs = binaryExpression.getROperand();
     final String rhsText = buildFromOffsetText(rhs, variable);
     final PsiJavaToken sign = binaryExpression.getOperationSign();
     final IElementType tokenType = sign.getTokenType();
     if (ExpressionUtils.isZero(lhs)) {
       if (tokenType.equals(JavaTokenType.MINUS)) {
         return '-' + rhsText;
       }
       return rhsText;
     }
     final String lhsText = buildFromOffsetText(lhs, variable);
     if (ExpressionUtils.isZero(rhs)) {
       return lhsText;
     }
     return collapseConstant(lhsText + sign.getText() + rhsText, variable);
   }
   return collapseConstant(expression.getText(), variable);
 }
 @Override
 public void doFix(Project project, ProblemDescriptor descriptor) {
   final PsiExpression expression = (PsiExpression) descriptor.getPsiElement();
   final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false);
   if (expectedType == null) {
     return;
   }
   final String expectedTypeText = expectedType.getCanonicalText();
   final String classToConstruct;
   if (s_boxingClasses.containsValue(expectedTypeText)) {
     classToConstruct = expectedTypeText;
   } else {
     final PsiType type = expression.getType();
     if (type == null) {
       return;
     }
     final String expressionTypeText = type.getCanonicalText();
     classToConstruct = s_boxingClasses.get(expressionTypeText);
   }
   if (shortcutReplace(expression, classToConstruct)) {
     return;
   }
   final PsiExpression strippedExpression = ParenthesesUtils.stripParentheses(expression);
   if (strippedExpression == null) {
     return;
   }
   @NonNls final String expressionText = strippedExpression.getText();
   @NonNls final String newExpression;
   if ("true".equals(expressionText)) {
     newExpression = "java.lang.Boolean.TRUE";
   } else if ("false".equals(expressionText)) {
     newExpression = "java.lang.Boolean.FALSE";
   } else {
     newExpression = classToConstruct + ".valueOf(" + expressionText + ')';
   }
   replaceExpression(expression, newExpression);
 }
 @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();
 }
 @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();
 }
 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);
   }
 }
 public static boolean expressionsAreEquivalent(
     @Nullable PsiExpression expression1, @Nullable PsiExpression expression2) {
   expression1 = ParenthesesUtils.stripParentheses(expression1);
   expression2 = ParenthesesUtils.stripParentheses(expression2);
   if (expression1 == null) {
     return expression2 == null;
   } else if (expression2 == null) {
     return false;
   }
   if (expression1.getClass() != expression2.getClass()) {
     return false;
   }
   if (expression1 instanceof PsiThisExpression) {
     return true;
   } else if (expression1 instanceof PsiSuperExpression) {
     return true;
   } else if (expression1 instanceof PsiLiteralExpression) {
     return literalExpressionsAreEquivalent(
         (PsiLiteralExpression) expression1, (PsiLiteralExpression) expression2);
   } else if (expression1 instanceof PsiClassObjectAccessExpression) {
     return classObjectAccessExpressionsAreEquivalent(
         (PsiClassObjectAccessExpression) expression1,
         (PsiClassObjectAccessExpression) expression2);
   } else if (expression1 instanceof PsiReferenceExpression) {
     return referenceExpressionsAreEquivalent(
         (PsiReferenceExpression) expression1, (PsiReferenceExpression) expression2);
   } else if (expression1 instanceof PsiMethodCallExpression) {
     return methodCallExpressionsAreEquivalent(
         (PsiMethodCallExpression) expression1, (PsiMethodCallExpression) expression2);
   } else if (expression1 instanceof PsiNewExpression) {
     return newExpressionsAreEquivalent(
         (PsiNewExpression) expression1, (PsiNewExpression) expression2);
   } else if (expression1 instanceof PsiArrayInitializerExpression) {
     return arrayInitializerExpressionsAreEquivalent(
         (PsiArrayInitializerExpression) expression1, (PsiArrayInitializerExpression) expression2);
   } else if (expression1 instanceof PsiTypeCastExpression) {
     return typeCastExpressionsAreEquivalent(
         (PsiTypeCastExpression) expression1, (PsiTypeCastExpression) expression2);
   } else if (expression1 instanceof PsiArrayAccessExpression) {
     return arrayAccessExpressionsAreEquivalent(
         (PsiArrayAccessExpression) expression2, (PsiArrayAccessExpression) expression1);
   } else if (expression1 instanceof PsiPrefixExpression) {
     return prefixExpressionsAreEquivalent(
         (PsiPrefixExpression) expression1, (PsiPrefixExpression) expression2);
   } else if (expression1 instanceof PsiPostfixExpression) {
     return postfixExpressionsAreEquivalent(
         (PsiPostfixExpression) expression1, (PsiPostfixExpression) expression2);
   } else if (expression1 instanceof PsiPolyadicExpression) {
     return polyadicExpressionsAreEquivalent(
         (PsiPolyadicExpression) expression1, (PsiPolyadicExpression) expression2);
   } else if (expression1 instanceof PsiAssignmentExpression) {
     return assignmentExpressionsAreEquivalent(
         (PsiAssignmentExpression) expression1, (PsiAssignmentExpression) expression2);
   } else if (expression1 instanceof PsiConditionalExpression) {
     return conditionalExpressionsAreEquivalent(
         (PsiConditionalExpression) expression1, (PsiConditionalExpression) expression2);
   } else if (expression1 instanceof PsiInstanceOfExpression) {
     return instanceofExpressionsAreEquivalent(
         (PsiInstanceOfExpression) expression1, (PsiInstanceOfExpression) expression2);
   }
   return false;
 }
 @Override
 public void visitBinaryExpression(PsiBinaryExpression expression) {
   super.visitBinaryExpression(expression);
   final IElementType operationTokenType = expression.getOperationTokenType();
   final PsiExpression lhs = ParenthesesUtils.stripParentheses(expression.getLOperand());
   final PsiExpression rhs = ParenthesesUtils.stripParentheses(expression.getROperand());
   final PsiBinaryExpression binaryExpression;
   final PsiExpression possibleInstanceofExpression;
   if (operationTokenType.equals(JavaTokenType.ANDAND)) {
     if (lhs instanceof PsiBinaryExpression) {
       binaryExpression = (PsiBinaryExpression) lhs;
       possibleInstanceofExpression = rhs;
     } else if (rhs instanceof PsiBinaryExpression) {
       binaryExpression = (PsiBinaryExpression) rhs;
       possibleInstanceofExpression = lhs;
     } else {
       return;
     }
     final IElementType tokenType = binaryExpression.getOperationTokenType();
     if (!tokenType.equals(JavaTokenType.NE)) {
       return;
     }
   } else if (operationTokenType.equals(JavaTokenType.OROR)) {
     if (lhs instanceof PsiBinaryExpression && rhs instanceof PsiPrefixExpression) {
       final PsiPrefixExpression prefixExpression = (PsiPrefixExpression) rhs;
       final IElementType prefixTokenType = prefixExpression.getOperationTokenType();
       if (!JavaTokenType.EXCL.equals(prefixTokenType)) {
         return;
       }
       binaryExpression = (PsiBinaryExpression) lhs;
       possibleInstanceofExpression =
           ParenthesesUtils.stripParentheses(prefixExpression.getOperand());
     } else if (rhs instanceof PsiBinaryExpression && lhs instanceof PsiPrefixExpression) {
       final PsiPrefixExpression prefixExpression = (PsiPrefixExpression) lhs;
       final IElementType prefixTokenType = prefixExpression.getOperationTokenType();
       if (!JavaTokenType.EXCL.equals(prefixTokenType)) {
         return;
       }
       binaryExpression = (PsiBinaryExpression) rhs;
       possibleInstanceofExpression =
           ParenthesesUtils.stripParentheses(prefixExpression.getOperand());
     } else {
       return;
     }
     final IElementType tokenType = binaryExpression.getOperationTokenType();
     if (!tokenType.equals(JavaTokenType.EQEQ)) {
       return;
     }
   } else {
     return;
   }
   final PsiReferenceExpression referenceExpression1 =
       getReferenceFromNullCheck(binaryExpression);
   if (referenceExpression1 == null) {
     return;
   }
   final PsiReferenceExpression referenceExpression2 =
       getReferenceFromInstanceofExpression(possibleInstanceofExpression);
   if (!referencesEqual(referenceExpression1, referenceExpression2)) {
     return;
   }
   registerError(binaryExpression);
 }
 @Nullable
 private static String getCollectionsAddAllText(PsiForStatement forStatement)
     throws IncorrectOperationException {
   final PsiExpression expression = forStatement.getCondition();
   final PsiBinaryExpression condition =
       (PsiBinaryExpression) ParenthesesUtils.stripParentheses(expression);
   if (condition == null) {
     return null;
   }
   final PsiStatement initialization = forStatement.getInitialization();
   if (initialization == null) {
     return null;
   }
   if (!(initialization instanceof PsiDeclarationStatement)) {
     return null;
   }
   final PsiDeclarationStatement declaration = (PsiDeclarationStatement) initialization;
   final PsiElement[] declaredElements = declaration.getDeclaredElements();
   if (declaredElements.length != 1) {
     return null;
   }
   final PsiElement declaredElement = declaredElements[0];
   if (!(declaredElement instanceof PsiLocalVariable)) {
     return null;
   }
   final PsiLocalVariable variable = (PsiLocalVariable) declaredElement;
   final String collectionText = buildCollectionText(forStatement);
   final PsiArrayAccessExpression arrayAccessExpression = getArrayAccessExpression(forStatement);
   if (arrayAccessExpression == null) {
     return null;
   }
   final PsiExpression arrayExpression = arrayAccessExpression.getArrayExpression();
   final String arrayText = arrayExpression.getText();
   final PsiExpression indexExpression = arrayAccessExpression.getIndexExpression();
   final String fromOffsetText = buildFromOffsetText(indexExpression, variable);
   if (fromOffsetText == null) {
     return null;
   }
   final PsiExpression limit;
   final IElementType tokenType = condition.getOperationTokenType();
   if (tokenType == JavaTokenType.LT || tokenType == JavaTokenType.LE) {
     limit = condition.getROperand();
   } else {
     limit = condition.getLOperand();
   }
   @NonNls
   final String toOffsetText =
       buildToOffsetText(limit, tokenType == JavaTokenType.LE || tokenType == JavaTokenType.GE);
   if (toOffsetText == null) {
     return null;
   }
   if (fromOffsetText.equals("0")
       && toOffsetText.equals(arrayText + ".length")
       && PsiUtil.isLanguageLevel5OrHigher(forStatement)) {
     return "java.util.Collections.addAll(" + collectionText + ',' + arrayText + ");";
   } else {
     @NonNls final StringBuilder buffer = new StringBuilder();
     buffer.append(collectionText);
     buffer.append('.');
     buffer.append("addAll(java.util.Arrays.asList(");
     buffer.append(arrayText);
     buffer.append(')');
     if (!fromOffsetText.equals("0") || !toOffsetText.equals(arrayText + ".length")) {
       buffer.append(".subList(");
       buffer.append(fromOffsetText);
       buffer.append(", ");
       buffer.append(toOffsetText);
       buffer.append(')');
     }
     buffer.append(");");
     return buffer.toString();
   }
 }
예제 #20
0
 public static boolean expressionsAreEquivalent(
     @Nullable PsiExpression exp1, @Nullable PsiExpression exp2) {
   if (exp1 == null && exp2 == null) {
     return true;
   }
   if (exp1 == null || exp2 == null) {
     return false;
   }
   final PsiExpression expToCompare1 = ParenthesesUtils.stripParentheses(exp1);
   final PsiExpression expToCompare2 = ParenthesesUtils.stripParentheses(exp2);
   if (expToCompare1 == null && expToCompare2 == null) {
     return true;
   }
   if (expToCompare1 == null || expToCompare2 == null) {
     return false;
   }
   if (expToCompare1.getClass() != expToCompare2.getClass()) {
     return false;
   }
   if (expToCompare1 instanceof PsiThisExpression) {
     return true;
   } else if (expToCompare1 instanceof PsiSuperExpression) {
     return true;
   } else if (expToCompare1 instanceof PsiLiteralExpression) {
     final String text1 = expToCompare1.getText();
     final String text2 = expToCompare2.getText();
     return text1.equals(text2);
   } else if (expToCompare1 instanceof PsiClassObjectAccessExpression) {
     final String text1 = expToCompare1.getText();
     final String text2 = expToCompare2.getText();
     return text1.equals(text2);
   } else if (expToCompare1 instanceof PsiReferenceExpression) {
     return referenceExpressionsAreEquivalent(
         (PsiReferenceExpression) expToCompare1, (PsiReferenceExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiMethodCallExpression) {
     return methodCallExpressionsAreEquivalent(
         (PsiMethodCallExpression) expToCompare1, (PsiMethodCallExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiNewExpression) {
     return newExpressionsAreEquivalent(
         (PsiNewExpression) expToCompare1, (PsiNewExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiArrayInitializerExpression) {
     return arrayInitializerExpressionsAreEquivalent(
         (PsiArrayInitializerExpression) expToCompare1,
         (PsiArrayInitializerExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiTypeCastExpression) {
     return typecastExpressionsAreEquivalent(
         (PsiTypeCastExpression) expToCompare1, (PsiTypeCastExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiArrayAccessExpression) {
     return arrayAccessExpressionsAreEquivalent(
         (PsiArrayAccessExpression) expToCompare2, (PsiArrayAccessExpression) expToCompare1);
   } else if (expToCompare1 instanceof PsiPrefixExpression) {
     return prefixExpressionsAreEquivalent(
         (PsiPrefixExpression) expToCompare1, (PsiPrefixExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiPostfixExpression) {
     return postfixExpressionsAreEquivalent(
         (PsiPostfixExpression) expToCompare1, (PsiPostfixExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiBinaryExpression) {
     return binaryExpressionsAreEquivalent(
         (PsiBinaryExpression) expToCompare1, (PsiBinaryExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiAssignmentExpression) {
     return assignmentExpressionsAreEquivalent(
         (PsiAssignmentExpression) expToCompare1, (PsiAssignmentExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiConditionalExpression) {
     return conditionalExpressionsAreEquivalent(
         (PsiConditionalExpression) expToCompare1, (PsiConditionalExpression) expToCompare2);
   } else if (expToCompare1 instanceof PsiInstanceOfExpression) {
     return instanceofExpressionsAreEquivalent(
         (PsiInstanceOfExpression) expToCompare1, (PsiInstanceOfExpression) expToCompare2);
   }
   return false;
 }