コード例 #1
0
  private static void reportOptionalOfNullableImprovements(
      ProblemsHolder holder, Set<PsiElement> reportedAnchors, Instruction[] instructions) {
    for (Instruction instruction : instructions) {
      if (instruction instanceof MethodCallInstruction) {
        final PsiExpression[] args = ((MethodCallInstruction) instruction).getArgs();
        if (args.length != 1) continue;

        final PsiExpression expr = args[0];

        if (((MethodCallInstruction) instruction).isOptionalAlwaysNullProblem()) {
          if (!reportedAnchors.add(expr)) continue;
          holder.registerProblem(
              expr,
              "Passing <code>null</code> argument to <code>Optional</code>",
              DfaOptionalSupport.createReplaceOptionalOfNullableWithEmptyFix(expr));
        } else if (((MethodCallInstruction) instruction).isOptionalAlwaysNotNullProblem()) {
          if (!reportedAnchors.add(expr)) continue;
          holder.registerProblem(
              expr,
              "Passing a non-null argument to <code>Optional</code>",
              DfaOptionalSupport.createReplaceOptionalOfNullableWithOfFix());
        }
      }
    }
  }
コード例 #2
0
  @Nullable
  private LocalQuickFix[] createNPEFixes(
      PsiExpression qualifier, PsiExpression expression, boolean onTheFly) {
    if (qualifier == null || expression == null) return null;
    if (qualifier instanceof PsiMethodCallExpression) return null;

    try {
      final List<LocalQuickFix> fixes = new SmartList<LocalQuickFix>();

      if (!(qualifier instanceof PsiLiteralExpression
          && ((PsiLiteralExpression) qualifier).getValue() == null)) {
        if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) {
          final Project project = qualifier.getProject();
          final PsiElementFactory elementFactory =
              JavaPsiFacade.getInstance(project).getElementFactory();
          final PsiBinaryExpression binary =
              (PsiBinaryExpression) elementFactory.createExpressionFromText("a != null", null);
          binary.getLOperand().replace(qualifier);
          ContainerUtil.addIfNotNull(fixes, createAssertFix(binary, expression));
        }

        addSurroundWithIfFix(qualifier, fixes, onTheFly);

        if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) {
          fixes.add(new ReplaceWithTernaryOperatorFix(qualifier));
        }
      }

      ContainerUtil.addIfNotNull(
          fixes, DfaOptionalSupport.registerReplaceOptionalOfWithOfNullableFix(qualifier));
      return fixes.isEmpty() ? null : fixes.toArray(new LocalQuickFix[fixes.size()]);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }