summaryrefslogtreecommitdiff
path: root/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/ArraysAsListWithZeroOrOneArgumentInspection.java
blob: 9502c8476c6c2384d97ba8b1916779e192bd3668 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.siyeh.ig.performance;

import com.intellij.codeInsight.Nullability;
import com.intellij.codeInspection.CommonQuickFixBundle;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.dataFlow.NullabilityUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.PsiReplacementUtil;
import com.siyeh.ig.psiutils.CommentTracker;
import com.siyeh.ig.psiutils.ConstructionUtils;
import com.siyeh.ig.psiutils.MethodCallUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Bas Leijdekkers
 */
public class ArraysAsListWithZeroOrOneArgumentInspection extends BaseInspection {

  @NotNull
  @Override
  protected String buildErrorString(Object... infos) {
    final Boolean isEmpty = (Boolean)infos[0];
    if (isEmpty.booleanValue()) {
      return InspectionGadgetsBundle.message("arrays.as.list.with.zero.arguments.problem.descriptor");
    }
    else {
      return InspectionGadgetsBundle.message("arrays.as.list.with.one.argument.problem.descriptor");
    }
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @Nullable
  @Override
  protected InspectionGadgetsFix buildFix(Object... infos) {
    final boolean isEmpty = (Boolean)infos[0];
    final boolean level9OrHigher = (Boolean)infos[1];
    return new ArraysAsListWithOneArgumentFix(isEmpty, level9OrHigher);
  }

  private static final class ArraysAsListWithOneArgumentFix extends InspectionGadgetsFix {

    private final boolean myEmpty;
    private final boolean myLevel9OrHigher;

    private ArraysAsListWithOneArgumentFix(boolean isEmpty, boolean level9OrHigher) {
      myEmpty = isEmpty;
      myLevel9OrHigher = level9OrHigher;
    }

    @NotNull
    @Override
    public String getName() {
      if (myLevel9OrHigher) return CommonQuickFixBundle.message("fix.replace.with.x", "List.of()");
      final @NonNls String call = myEmpty ? "Collections.emptyList()" : "Collections.singletonList()";
      return CommonQuickFixBundle.message("fix.replace.with.x", call);
    }

    @NotNull
    @Override
    public String getFamilyName() {
      return CommonQuickFixBundle.message("fix.simplify");
    }

    @Override
    protected void doFix(Project project, ProblemDescriptor descriptor) {
      final PsiElement element = descriptor.getPsiElement().getParent().getParent();
      if (!(element instanceof PsiMethodCallExpression)) {
        return;
      }
      final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)element;
      final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
      final PsiReferenceParameterList parameterList = methodExpression.getParameterList();
      final CommentTracker commentTracker = new CommentTracker();
      final String parameterText = parameterList != null ? commentTracker.text(parameterList) : "";
      if (myEmpty) {
        if (myLevel9OrHigher) {
          PsiReplacementUtil.replaceExpressionAndShorten(methodCallExpression, "java.util.List." + parameterText + "of()",
                                                         commentTracker);
        }
        else {
          PsiReplacementUtil.replaceExpressionAndShorten(methodCallExpression, "java.util.Collections." + parameterText + "emptyList()",
                                                         commentTracker);
        }
      }
      else {
        final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
        if (myLevel9OrHigher) {
          PsiReplacementUtil.replaceExpressionAndShorten(methodCallExpression,
                                                         "java.util.List." + parameterText + "of" + commentTracker.text(argumentList),
                                                         commentTracker);
        }
        else {
          PsiReplacementUtil.replaceExpressionAndShorten(methodCallExpression,
                                                         "java.util.Collections." + parameterText + "singletonList" + commentTracker.text(argumentList),
                                                         commentTracker);
        }
      }
    }
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new ArrayAsListWithOneArgumentVisitor();
  }

  private static class ArrayAsListWithOneArgumentVisitor extends BaseInspectionVisitor {

    @Override
    public void visitMethodCallExpression(PsiMethodCallExpression expression) {
      super.visitMethodCallExpression(expression);
      final PsiReferenceExpression methodExpression = expression.getMethodExpression();
      final @NonNls String methodName = methodExpression.getReferenceName();
      if (!"asList".equals(methodName)) {
        return;
      }
      final PsiExpressionList argumentList = expression.getArgumentList();
      final PsiExpression[] arguments = argumentList.getExpressions();
      if (arguments.length > 1) return;

      boolean isLevel9Plus = PsiUtil.isLanguageLevel9OrHigher(expression);
      boolean empty = false;
      if (arguments.length == 0) {
        empty = true;
      }
      else {
        final PsiExpression argument = arguments[0];
        if (!MethodCallUtils.isVarArgCall(expression)) {
          if (!ConstructionUtils.isEmptyArrayInitializer(argument)) {
            return;
          }
          empty = true;
        }
        if (isLevel9Plus && NullabilityUtil.getExpressionNullability(argument, true) != Nullability.NOT_NULL) {
          // Avoid suggesting List.of with potentially nullable argument
          isLevel9Plus = false;
        }
      }
      final PsiMethod method = expression.resolveMethod();
      if (method == null) {
        return;
      }
      final PsiClass containingClass = method.getContainingClass();
      if (containingClass == null) {
        return;
      }
      final String className = containingClass.getQualifiedName();
      if (!"java.util.Arrays".equals(className)) {
        return;
      }
      registerMethodCallError(expression, empty, isLevel9Plus);
    }
  }
}