private static void checkSillyAssignment(
     PsiAssignmentExpression assignment, ProblemsHolder holder) {
   if (assignment.getOperationTokenType() != JavaTokenType.EQ) return;
   PsiExpression lExpression = assignment.getLExpression();
   PsiExpression rExpression = assignment.getRExpression();
   if (rExpression == null) return;
   lExpression = PsiUtil.deparenthesizeExpression(lExpression);
   rExpression = PsiUtil.deparenthesizeExpression(rExpression);
   if (!(lExpression instanceof PsiReferenceExpression)) return;
   PsiReferenceExpression rRef;
   if (!(rExpression instanceof PsiReferenceExpression)) {
     if (!(rExpression instanceof PsiAssignmentExpression)) return;
     final PsiAssignmentExpression rAssignmentExpression = (PsiAssignmentExpression) rExpression;
     final PsiExpression assignee =
         PsiUtil.deparenthesizeExpression(rAssignmentExpression.getLExpression());
     if (!(assignee instanceof PsiReferenceExpression)) return;
     rRef = (PsiReferenceExpression) assignee;
   } else {
     rRef = (PsiReferenceExpression) rExpression;
   }
   PsiReferenceExpression lRef = (PsiReferenceExpression) lExpression;
   PsiManager manager = assignment.getManager();
   if (!sameInstanceReferences(lRef, rRef, manager)) return;
   final PsiVariable variable = (PsiVariable) lRef.resolve();
   if (variable == null) return;
   holder.registerProblem(
       assignment,
       InspectionsBundle.message("assignment.to.itself.problem.descriptor", variable.getName()),
       ProblemHighlightType.LIKE_UNUSED_SYMBOL);
 }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   PsiElement element = descriptor.getStartElement();
   if (!(element instanceof PsiLoopStatement)) return;
   PsiLoopStatement loop = (PsiLoopStatement) element;
   IteratorDeclaration declaration;
   declaration = IteratorDeclaration.fromLoop(loop);
   if (declaration == null) return;
   PsiStatement body = loop.getBody();
   if (!(body instanceof PsiBlockStatement)) return;
   PsiStatement[] statements = ((PsiBlockStatement) body).getCodeBlock().getStatements();
   PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   String replacement = null;
   CommentTracker ct = new CommentTracker();
   if (statements.length == 2 && statements[1] instanceof PsiIfStatement) {
     PsiVariable variable = declaration.getNextElementVariable(statements[0]);
     if (variable == null) return;
     PsiExpression condition = ((PsiIfStatement) statements[1]).getCondition();
     if (condition == null) return;
     replacement = generateRemoveIf(declaration, ct, condition, variable.getName());
   } else if (statements.length == 1 && statements[0] instanceof PsiIfStatement) {
     PsiExpression condition = ((PsiIfStatement) statements[0]).getCondition();
     if (condition == null) return;
     PsiElement ref = declaration.findOnlyIteratorRef(condition);
     if (ref != null) {
       PsiElement call = ref.getParent().getParent();
       if (!declaration.isIteratorMethodCall(call, "next")) return;
       PsiType type = ((PsiExpression) call).getType();
       JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
       SuggestedNameInfo info =
           javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type);
       if (info.names.length == 0) {
         info =
             javaCodeStyleManager.suggestVariableName(
                 VariableKind.PARAMETER, "value", null, type);
       }
       String paramName =
           javaCodeStyleManager.suggestUniqueVariableName(info, condition, true).names[0];
       ct.replace(call, factory.createIdentifier(paramName));
       replacement = generateRemoveIf(declaration, ct, condition, paramName);
     }
   }
   if (replacement == null) return;
   ct.delete(declaration.getIterator());
   PsiElement result = ct.replaceAndRestoreComments(loop, replacement);
   LambdaCanBeMethodReferenceInspection.replaceAllLambdasWithMethodReferences(result);
   CodeStyleManager.getInstance(project).reformat(result);
 }
Пример #3
0
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiElement element = descriptor.getPsiElement();
      final PsiModifierListOwner psiElement =
          PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class);
      if (psiElement != null) {
        RefJavaElement refElement =
            (RefJavaElement) (myManager != null ? myManager.getReference(psiElement) : null);
        try {
          if (psiElement instanceof PsiVariable) {
            ((PsiVariable) psiElement).normalizeDeclaration();
          }
          final PsiModifierList modifierList = psiElement.getModifierList();
          LOG.assertTrue(modifierList != null);
          modifierList.setModifierProperty(PsiModifier.FINAL, true);
          modifierList.setModifierProperty(PsiModifier.VOLATILE, false);
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }

        if (refElement != null) {
          RefJavaUtil.getInstance().setIsFinal(refElement, true);
        }
      }
    }
  private static String getConstantValueText(Object value, @Nullable PsiVariable constant) {
    if (constant != null) {
      return constant instanceof PsiMember
          ? PsiUtil.getMemberQualifiedName((PsiMember) constant)
          : constant.getName();
    }

    return value instanceof String
        ? "\"" + StringUtil.escapeStringCharacters((String) value) + "\""
        : String.valueOf(value);
  }
  /**
   * @return true if both expressions resolve to the same variable/class or field in the same
   *     instance of the class
   */
  private static boolean sameInstanceReferences(
      @Nullable PsiJavaCodeReferenceElement lRef,
      @Nullable PsiJavaCodeReferenceElement rRef,
      PsiManager manager) {
    if (lRef == null && rRef == null) return true;
    if (lRef == null || rRef == null) return false;
    PsiElement lResolved = lRef.resolve();
    PsiElement rResolved = rRef.resolve();
    if (!manager.areElementsEquivalent(lResolved, rResolved)) return false;
    if (!(lResolved instanceof PsiVariable)) return false;
    final PsiVariable variable = (PsiVariable) lResolved;
    if (variable.hasModifierProperty(PsiModifier.STATIC)) return true;

    final PsiElement lQualifier = lRef.getQualifier();
    final PsiElement rQualifier = rRef.getQualifier();
    if (lQualifier instanceof PsiJavaCodeReferenceElement
        && rQualifier instanceof PsiJavaCodeReferenceElement) {
      return sameInstanceReferences(
          (PsiJavaCodeReferenceElement) lQualifier,
          (PsiJavaCodeReferenceElement) rQualifier,
          manager);
    }

    if (Comparing.equal(lQualifier, rQualifier)) return true;
    boolean lThis =
        lQualifier == null
            || lQualifier instanceof PsiThisExpression
            || lQualifier instanceof PsiSuperExpression;
    boolean rThis =
        rQualifier == null
            || rQualifier instanceof PsiThisExpression
            || rQualifier instanceof PsiSuperExpression;
    if (lThis && rThis) {
      final PsiJavaCodeReferenceElement llQualifier = getQualifier(lQualifier);
      final PsiJavaCodeReferenceElement rrQualifier = getQualifier(rQualifier);
      return sameInstanceReferences(llQualifier, rrQualifier, manager);
    }
    return false;
  }
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!FileModificationService.getInstance()
          .preparePsiElementForWrite(descriptor.getPsiElement())) return;
      final PsiModifierListOwner element =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiModifierListOwner.class);
      if (element != null) {
        RefElement refElement = null;
        if (myManager != null) {
          refElement = myManager.getReference(element);
        }
        try {
          if (element instanceof PsiVariable) {
            ((PsiVariable) element).normalizeDeclaration();
          }

          PsiModifierList list = element.getModifierList();

          LOG.assertTrue(list != null);

          if (element instanceof PsiMethod) {
            PsiMethod psiMethod = (PsiMethod) element;
            PsiClass containingClass = psiMethod.getContainingClass();
            if (containingClass != null
                && containingClass.getParent() instanceof PsiFile
                && myHint == PsiModifier.PRIVATE
                && list.hasModifierProperty(PsiModifier.FINAL)) {
              list.setModifierProperty(PsiModifier.FINAL, false);
            }
          }

          list.setModifierProperty(myHint, true);
          if (refElement instanceof RefJavaElement) {
            RefJavaUtil.getInstance().setAccessModifier((RefJavaElement) refElement, myHint);
          }
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }
    }
  private static void reportConstantReferenceValues(
      ProblemsHolder holder, StandardInstructionVisitor visitor, Set<PsiElement> reportedAnchors) {
    for (Pair<PsiReferenceExpression, DfaConstValue> pair : visitor.getConstantReferenceValues()) {
      PsiReferenceExpression ref = pair.first;
      if (!reportedAnchors.add(ref)) {
        continue;
      }

      final Object value = pair.second.getValue();
      PsiVariable constant = pair.second.getConstant();
      final String presentableName = constant != null ? constant.getName() : String.valueOf(value);
      final String exprText = getConstantValueText(value, constant);
      if (presentableName == null || exprText == null) {
        continue;
      }

      holder.registerProblem(
          ref,
          "Value <code>#ref</code> #loc is always '" + presentableName + "'",
          new LocalQuickFix() {
            @NotNull
            @Override
            public String getName() {
              return "Replace with '" + presentableName + "'";
            }

            @NotNull
            @Override
            public String getFamilyName() {
              return "Replace with constant value";
            }

            @Override
            public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
              if (!FileModificationService.getInstance()
                  .preparePsiElementsForWrite(descriptor.getPsiElement())) {
                return;
              }

              JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
              PsiElement newElement =
                  descriptor
                      .getPsiElement()
                      .replace(facade.getElementFactory().createExpressionFromText(exprText, null));
              newElement =
                  JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement);
              if (newElement instanceof PsiJavaCodeReferenceElement) {
                PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement) newElement;
                PsiElement target = ref.resolve();
                String shortName = ref.getReferenceName();
                if (target != null
                    && shortName != null
                    && ref.isQualified()
                    && facade.getResolveHelper().resolveReferencedVariable(shortName, newElement)
                        == target) {
                  newElement.replace(
                      facade.getElementFactory().createExpressionFromText(shortName, null));
                }
              }
            }
          });
    }
  }
  private static void reportConstantReferenceValues(
      ProblemsHolder holder, StandardInstructionVisitor visitor, Set<PsiElement> reportedAnchors) {
    for (Pair<PsiReferenceExpression, DfaConstValue> pair : visitor.getConstantReferenceValues()) {
      PsiReferenceExpression ref = pair.first;
      if (ref.getParent() instanceof PsiReferenceExpression || !reportedAnchors.add(ref)) {
        continue;
      }

      final Object value = pair.second.getValue();
      PsiVariable constant = pair.second.getConstant();
      final String presentableName = constant != null ? constant.getName() : String.valueOf(value);
      final String exprText = String.valueOf(value);
      if (presentableName == null || exprText == null) {
        continue;
      }

      holder.registerProblem(
          ref,
          "Value <code>#ref</code> #loc is always '" + presentableName + "'",
          new LocalQuickFix() {
            @NotNull
            @Override
            public String getName() {
              return "Replace with '" + presentableName + "'";
            }

            @NotNull
            @Override
            public String getFamilyName() {
              return "Replace with constant value";
            }

            @Override
            public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
              if (!FileModificationService.getInstance()
                  .preparePsiElementsForWrite(descriptor.getPsiElement())) {
                return;
              }

              PsiElement problemElement = descriptor.getPsiElement();
              if (problemElement == null) return;

              PsiMethodCallExpression call =
                  problemElement.getParent() instanceof PsiExpressionList
                          && problemElement.getParent().getParent()
                              instanceof PsiMethodCallExpression
                      ? (PsiMethodCallExpression) problemElement.getParent().getParent()
                      : null;
              PsiMethod targetMethod = call == null ? null : call.resolveMethod();

              JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
              problemElement.replace(
                  facade.getElementFactory().createExpressionFromText(exprText, null));

              if (targetMethod != null) {
                ExtractMethodUtil.addCastsToEnsureResolveTarget(targetMethod, call);
              }
            }
          });
    }
  }