public static String buildCollectionText(PsiForStatement forStatement) {
   PsiStatement body = forStatement.getBody();
   while (body instanceof PsiBlockStatement) {
     final PsiBlockStatement blockStatement = (PsiBlockStatement) body;
     final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
     final PsiStatement[] statements = codeBlock.getStatements();
     if (statements.length == 2) {
       body = statements[1];
     } else if (statements.length == 1) {
       body = statements[0];
     } else {
       return null;
     }
   }
   if (!(body instanceof PsiExpressionStatement)) {
     return null;
   }
   final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) body;
   final PsiExpression expression = expressionStatement.getExpression();
   if (!(expression instanceof PsiMethodCallExpression)) {
     return null;
   }
   final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
   final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
   final PsiElement qualifier = methodExpression.getQualifier();
   if (qualifier == null) {
     // fixme for when the array is added to 'this'
     return null;
   }
   return qualifier.getText();
 }
  public static int findFieldAssignmentAnchor(
      final PsiStatement[] statements,
      final @Nullable Ref<Pair<PsiField, Boolean>> anchorRef,
      final PsiClass targetClass,
      final PsiParameter myParameter) {
    int i = 0;
    for (; i < statements.length; i++) {
      PsiStatement psiStatement = statements[i];

      if (psiStatement instanceof PsiExpressionStatement) {
        PsiExpressionStatement expressionStatement = (PsiExpressionStatement) psiStatement;
        PsiExpression expression = expressionStatement.getExpression();

        if (expression instanceof PsiMethodCallExpression) {
          PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
          String text = methodCallExpression.getMethodExpression().getText();
          if (text.equals("super") || text.equals("this")) {
            continue;
          }
        } else if (expression instanceof PsiAssignmentExpression) {
          PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) expression;
          PsiExpression lExpression = assignmentExpression.getLExpression();
          PsiExpression rExpression = assignmentExpression.getRExpression();

          if (!(lExpression instanceof PsiReferenceExpression)) break;
          if (!(rExpression instanceof PsiReferenceExpression)) break;

          PsiReferenceExpression lReference = (PsiReferenceExpression) lExpression;
          PsiReferenceExpression rReference = (PsiReferenceExpression) rExpression;

          PsiElement lElement = lReference.resolve();
          PsiElement rElement = rReference.resolve();

          if (!(lElement instanceof PsiField)
              || ((PsiField) lElement).getContainingClass() != targetClass) break;
          if (!(rElement instanceof PsiParameter)) break;

          if (myParameter.getTextRange().getStartOffset()
              < rElement.getTextRange().getStartOffset()) {
            if (anchorRef != null) {
              anchorRef.set(Pair.create((PsiField) lElement, Boolean.TRUE));
            }
            break;
          }

          if (anchorRef != null) {
            anchorRef.set(Pair.create((PsiField) lElement, Boolean.FALSE));
          }
          continue;
        }
      }

      break;
    }
    return i;
  }
  public static void translate(PsiExpressionStatement element, TranslationContext ctx) {

    boolean loopDeclaration = false;
    PsiElement parent = element.getParent();
    if (parent instanceof PsiLoopStatement
        && !((PsiLoopStatement) parent).getBody().equals(element)) {
      loopDeclaration = true;
    }
    if (!loopDeclaration) {
      ctx.print("");
    }
    ExpressionTranslator.translate(element.getExpression(), ctx);
    if (!loopDeclaration) {
      ctx.append(";\n");
    }
  }
 @Override
 public void visitExpressionStatement(@NotNull PsiExpressionStatement statement) {
   super.visitExpressionStatement(statement);
   final PsiExpression expression = statement.getExpression();
   if (!(expression instanceof PsiMethodCallExpression)) {
     return;
   }
   final PsiMethodCallExpression call = (PsiMethodCallExpression) expression;
   final PsiMethod method = call.resolveMethod();
   if (method == null || method.isConstructor()) {
     return;
   }
   final PsiType returnType = method.getReturnType();
   if (PsiType.VOID.equals(returnType)) {
     return;
   }
   final PsiClass aClass = method.getContainingClass();
   if (aClass == null) {
     return;
   }
   if (PsiUtilCore.hasErrorElementChild(statement)) {
     return;
   }
   if (m_reportAllNonLibraryCalls && !LibraryUtil.classIsInLibrary(aClass)) {
     registerMethodCallError(call, aClass);
     return;
   }
   final PsiReferenceExpression methodExpression = call.getMethodExpression();
   final String methodName = methodExpression.getReferenceName();
   if (methodName == null) {
     return;
   }
   for (int i = 0; i < methodNamePatterns.size(); i++) {
     final String methodNamePattern = methodNamePatterns.get(i);
     if (!methodNamesMatch(methodName, methodNamePattern)) {
       continue;
     }
     final String className = classNames.get(i);
     if (!InheritanceUtil.isInheritor(aClass, className)) {
       continue;
     }
     registerMethodCallError(call, aClass);
     return;
   }
 }
 private static void addSuperCall(
     JavaChangeInfo changeInfo, PsiMethod constructor, PsiMethod callee, final UsageInfo[] usages)
     throws IncorrectOperationException {
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(constructor.getProject());
   PsiExpressionStatement superCall =
       (PsiExpressionStatement) factory.createStatementFromText("super();", constructor);
   PsiCodeBlock body = constructor.getBody();
   assert body != null;
   PsiStatement[] statements = body.getStatements();
   if (statements.length > 0) {
     superCall = (PsiExpressionStatement) body.addBefore(superCall, statements[0]);
   } else {
     superCall = (PsiExpressionStatement) body.add(superCall);
   }
   PsiMethodCallExpression callExpression = (PsiMethodCallExpression) superCall.getExpression();
   final PsiClass aClass = constructor.getContainingClass();
   final PsiClass baseClass = changeInfo.getMethod().getContainingClass();
   final PsiSubstitutor substitutor =
       TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY);
   processMethodUsage(
       callExpression.getMethodExpression(), changeInfo, true, false, callee, substitutor, usages);
 }
  private static PsiStatement createAssignment(
      PsiLocalVariable local, String fieldname, PsiElementFactory factory) {
    try {
      String pattern = fieldname + "=0;";
      PsiExpressionStatement statement =
          (PsiExpressionStatement) factory.createStatementFromText(pattern, null);
      statement =
          (PsiExpressionStatement)
              CodeStyleManager.getInstance(local.getProject()).reformat(statement);

      PsiAssignmentExpression expr = (PsiAssignmentExpression) statement.getExpression();
      final PsiExpression initializer =
          RefactoringUtil.convertInitializerToNormalExpression(
              local.getInitializer(), local.getType());
      expr.getRExpression().replace(initializer);

      return statement;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
 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 isInThisOrSuperCall(PsiNewExpression newExpression) {
   boolean inFirstConstructorLine = false;
   final PsiExpressionStatement expressionStatement =
       PsiTreeUtil.getParentOfType(newExpression, PsiExpressionStatement.class);
   if (expressionStatement != null) {
     final PsiExpression expression = expressionStatement.getExpression();
     if (expression instanceof PsiMethodCallExpression) {
       final PsiReferenceExpression methodExpression =
           ((PsiMethodCallExpression) expression).getMethodExpression();
       final PsiElement resolve = methodExpression.resolve();
       if (resolve instanceof PsiMethod && ((PsiMethod) resolve).isConstructor()) {
         final PsiElement referenceNameElement = methodExpression.getReferenceNameElement();
         if (referenceNameElement != null) {
           if (Comparing.strEqual(referenceNameElement.getText(), PsiKeyword.THIS)
               || Comparing.strEqual(referenceNameElement.getText(), PsiKeyword.SUPER)) {
             inFirstConstructorLine = true;
           }
         }
       }
     }
   }
   return inFirstConstructorLine;
 }
Exemplo n.º 9
0
  private static void modifySuperCall(
      final PsiMethod subConstructor, final Set<PsiParameter> parametersToPassToSuper) {
    final PsiCodeBlock body = subConstructor.getBody();
    if (body != null) {
      PsiMethodCallExpression superCall = null;
      final PsiStatement[] statements = body.getStatements();
      if (statements.length > 0) {
        if (statements[0] instanceof PsiExpressionStatement) {
          final PsiExpression expression = ((PsiExpressionStatement) statements[0]).getExpression();
          if (expression instanceof PsiMethodCallExpression) {
            final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression;
            if ("super".equals(methodCall.getMethodExpression().getText())) {
              superCall = methodCall;
            }
          }
        }
      }

      final PsiElementFactory factory =
          JavaPsiFacade.getInstance(subConstructor.getProject()).getElementFactory();
      try {
        if (superCall == null) {
          PsiExpressionStatement statement =
              (PsiExpressionStatement) factory.createStatementFromText("super();", null);
          statement = (PsiExpressionStatement) body.addAfter(statement, null);
          superCall = (PsiMethodCallExpression) statement.getExpression();
        }

        final PsiExpressionList argList = superCall.getArgumentList();
        for (final PsiParameter parameter : parametersToPassToSuper) {
          argList.add(factory.createExpressionFromText(parameter.getName(), null));
        }
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  }
 @Nullable
 private static String getCollectionsAddAllText(PsiForeachStatement foreachStatement)
     throws IncorrectOperationException {
   final PsiStatement body = getBody(foreachStatement);
   if (!(body instanceof PsiExpressionStatement)) {
     return null;
   }
   final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) body;
   final PsiMethodCallExpression methodCallExpression =
       (PsiMethodCallExpression) expressionStatement.getExpression();
   final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
   final PsiElement collection = methodExpression.getQualifier();
   if (collection == null) {
     // fixme for when the array is added to 'this'
     return null;
   }
   final String collectionText = collection.getText();
   final PsiExpression iteratedValue = foreachStatement.getIteratedValue();
   if (iteratedValue == null) {
     return null;
   }
   final String arrayText = iteratedValue.getText();
   @NonNls final StringBuilder buffer = new StringBuilder();
   if (PsiUtil.isLanguageLevel5OrHigher(foreachStatement)) {
     buffer.append("java.util.Collections.addAll(");
     buffer.append(collectionText);
     buffer.append(',');
     buffer.append(arrayText);
     buffer.append(");");
   } else {
     buffer.append(collectionText);
     buffer.append(".addAll(java.util.Arrays.asList(");
     buffer.append(arrayText);
     buffer.append("));");
   }
   return buffer.toString();
 }
 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 static PsiMethodCallExpression extractAddCall(
      PsiStatement body, PsiIfStatement ifStatement) {
    if (ifStatement != null) {
      final PsiStatement thenBranch = ifStatement.getThenBranch();
      return extractAddCall(thenBranch, null);
    }
    PsiExpressionStatement stmt = null;
    if (body instanceof PsiBlockStatement) {
      final PsiStatement[] statements = ((PsiBlockStatement) body).getCodeBlock().getStatements();
      if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) {
        stmt = (PsiExpressionStatement) statements[0];
      }
    } else if (body instanceof PsiExpressionStatement) {
      stmt = (PsiExpressionStatement) body;
    }

    if (stmt != null) {
      final PsiExpression expression = stmt.getExpression();
      if (expression instanceof PsiMethodCallExpression) {
        return (PsiMethodCallExpression) expression;
      }
    }
    return null;
  }
 private static boolean expressionStatementsAreEquivalent(
     @NotNull PsiExpressionStatement statement1, @NotNull PsiExpressionStatement statement2) {
   final PsiExpression expression1 = statement1.getExpression();
   final PsiExpression expression2 = statement2.getExpression();
   return expressionsAreEquivalent(expression1, expression2);
 }
 @Override
 public void visitExpressionStatement(PsiExpressionStatement statement) {
   statement.getExpression().acceptChildren(this);
 }
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiForeachStatement foreachStatement =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiForeachStatement.class);
      if (foreachStatement != null) {
        if (!FileModificationService.getInstance().preparePsiElementForWrite(foreachStatement))
          return;
        PsiStatement body = foreachStatement.getBody();
        final PsiExpression iteratedValue = foreachStatement.getIteratedValue();
        if (body != null && iteratedValue != null) {
          restoreComments(foreachStatement, body);

          final PsiParameter parameter = foreachStatement.getIterationParameter();
          final PsiIfStatement ifStmt = extractIfStatement(body);

          StringBuilder buffer = new StringBuilder(getIteratedValueText(iteratedValue));
          if (ifStmt != null) {
            final PsiStatement thenBranch = ifStmt.getThenBranch();
            LOG.assertTrue(thenBranch != null);
            buffer.append(".stream()");
            buffer.append(createFiltersChainText(body, parameter, ifStmt));
            body = thenBranch;
          }

          buffer.append(".").append(getForEachMethodName()).append("(");

          final String functionalExpressionText =
              createForEachFunctionalExpressionText(project, body, parameter);
          final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
          PsiExpressionStatement callStatement =
              (PsiExpressionStatement)
                  elementFactory.createStatementFromText(
                      buffer.toString() + functionalExpressionText + ");", foreachStatement);
          callStatement = (PsiExpressionStatement) foreachStatement.replace(callStatement);

          final PsiExpressionList argumentList =
              ((PsiCallExpression) callStatement.getExpression()).getArgumentList();
          LOG.assertTrue(argumentList != null, callStatement.getText());
          final PsiExpression[] expressions = argumentList.getExpressions();
          LOG.assertTrue(expressions.length == 1);

          if (expressions[0] instanceof PsiFunctionalExpression
              && ((PsiFunctionalExpression) expressions[0]).getFunctionalInterfaceType() == null) {
            callStatement =
                (PsiExpressionStatement)
                    callStatement.replace(
                        elementFactory.createStatementFromText(
                            buffer.toString()
                                + "("
                                + parameter.getText()
                                + ") -> "
                                + wrapInBlock(body)
                                + ");",
                            callStatement));
          }

          simplifyRedundantCast(callStatement);

          CodeStyleManager.getInstance(project)
              .reformat(
                  JavaCodeStyleManager.getInstance(project).shortenClassReferences(callStatement));
        }
      }
    }
  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);
  }