summaryrefslogtreecommitdiff
path: root/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java
blob: 69c2bad8242b211bb39a3a97949375bed78fc10d (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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
 * Copyright 2003-2014 Dave Griffith, Bas Leijdekkers
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.siyeh.ig.performance;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.HardcodedMethodConstants;
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.BoolUtils;
import com.siyeh.ig.psiutils.EquivalenceChecker;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.TypeUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

public class StringEqualsEmptyStringInspection extends BaseInspection {

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("string.equals.empty.string.display.name");
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    final boolean useIsEmpty = ((Boolean)infos[0]).booleanValue();
    if (useIsEmpty) {
      return InspectionGadgetsBundle.message("string.equals.empty.string.is.empty.problem.descriptor");
    } else {
      return InspectionGadgetsBundle.message("string.equals.empty.string.problem.descriptor");
    }
  }

  @Override
  public InspectionGadgetsFix buildFix(Object... infos) {
    final boolean useIsEmpty = ((Boolean)infos[0]).booleanValue();
    return new StringEqualsEmptyStringFix(useIsEmpty);
  }

  private static class StringEqualsEmptyStringFix extends InspectionGadgetsFix {

    private final boolean useIsEmpty;

    public StringEqualsEmptyStringFix(boolean useIsEmpty) {
      this.useIsEmpty = useIsEmpty;
    }

    @Override
    @NotNull
    public String getName() {
      if (useIsEmpty) {
        return InspectionGadgetsBundle.message("string.equals.empty.string.isempty.quickfix");
      }
      else {
        return InspectionGadgetsBundle.message("string.equals.empty.string.quickfix");
      }
    }

    @NotNull
    @Override
    public String getFamilyName() {
      return "Simplify empty string check";
    }

    @Override
    public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
      final PsiIdentifier name = (PsiIdentifier)descriptor.getPsiElement();
      final PsiReferenceExpression expression = (PsiReferenceExpression)name.getParent();
      if (expression == null) {
        return;
      }
      final PsiMethodCallExpression call = (PsiMethodCallExpression)expression.getParent();
      final PsiExpressionList argumentList = call.getArgumentList();
      final PsiExpression[] arguments = argumentList.getExpressions();
      if (arguments.length == 0) {
        return;
      }
      final PsiExpression qualifier = expression.getQualifierExpression();
      final PsiExpression argument = arguments[0];
      final PsiExpression checkedExpression;
      final boolean addNullCheck;
      if (ExpressionUtils.isEmptyStringLiteral(argument)) {
        checkedExpression = getCheckedExpression(qualifier);
        addNullCheck = false;
      }
      else {
        checkedExpression = getCheckedExpression(argument);
        addNullCheck = !isCheckedForNull(checkedExpression);
      }
      final StringBuilder newExpression;
      if (addNullCheck) {
        newExpression = new StringBuilder(checkedExpression.getText());
        newExpression.append("!=null&&");
      } else {
        newExpression = new StringBuilder("");
      }
      final PsiElement parent = call.getParent();
      final PsiExpression expressionToReplace;
      if (parent instanceof PsiExpression) {
        final PsiExpression parentExpression = (PsiExpression)parent;
        if (BoolUtils.isNegation(parentExpression)) {
          expressionToReplace = parentExpression;
          if (useIsEmpty) {
            newExpression.append('!').append(checkedExpression.getText()).append(".isEmpty()");
          }
          else {
            newExpression.append(checkedExpression.getText()).append(".length()!=0");
          }
        }
        else {
          expressionToReplace = call;
          if (useIsEmpty) {
            newExpression.append(checkedExpression.getText()).append(".isEmpty()");
          }
          else {
            newExpression.append(checkedExpression.getText()).append(".length()==0");
          }
        }
      }
      else {
        expressionToReplace = call;
        if (useIsEmpty) {
          newExpression.append(checkedExpression.getText()).append(".isEmpty()");
        }
        else {
          newExpression.append(checkedExpression.getText()).append(".length()==0");
        }
      }
      PsiReplacementUtil.replaceExpression(expressionToReplace, newExpression.toString());
    }

    private static boolean isCheckedForNull(PsiExpression expression) {
      final PsiPolyadicExpression polyadicExpression =
        PsiTreeUtil.getParentOfType(expression, PsiPolyadicExpression.class, true, PsiStatement.class, PsiVariable.class);
      if (polyadicExpression == null) {
        return false;
      }
      final IElementType tokenType = polyadicExpression.getOperationTokenType();
      for (PsiExpression operand : polyadicExpression.getOperands()) {
        if (PsiTreeUtil.isAncestor(operand, expression, true)) {
          return false;
        }
        if (!(operand instanceof PsiBinaryExpression)) {
          continue;
        }
        final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)operand;
        final IElementType operationTokenType = binaryExpression.getOperationTokenType();
        if (JavaTokenType.ANDAND.equals(tokenType)) {
          if (!JavaTokenType.NE.equals(operationTokenType)) {
            continue;
          }
        }
        else if (JavaTokenType.OROR.equals(tokenType)) {
          if (!JavaTokenType.EQEQ.equals(operationTokenType)) {
            continue;
          }
        }
        else {
          continue;
        }
        final PsiExpression lhs = binaryExpression.getLOperand();
        final PsiExpression rhs = binaryExpression.getROperand();
        if (rhs == null) {
          continue;
        }
        if (PsiType.NULL.equals(lhs.getType()) && EquivalenceChecker.expressionsAreEquivalent(expression, rhs)) {
          return true;
        }
        else if (PsiType.NULL.equals(rhs.getType()) && EquivalenceChecker.expressionsAreEquivalent(expression, lhs)) {
          return true;
        }
      }
      return false;
    }

    private PsiExpression getCheckedExpression(PsiExpression expression) {
      if (useIsEmpty || !(expression instanceof PsiMethodCallExpression)) {
        return expression;
      }
      // to replace stringBuffer.toString().equals("") with
      // stringBuffer.length() == 0
      final PsiMethodCallExpression callExpression = (PsiMethodCallExpression)expression;
      final PsiReferenceExpression methodExpression = callExpression.getMethodExpression();
      final String referenceName = methodExpression.getReferenceName();
      final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
      if (qualifierExpression == null) {
        return expression;
      }
      final PsiType type = qualifierExpression.getType();
      if (HardcodedMethodConstants.TO_STRING.equals(referenceName) && type != null && (type.equalsToText(
        CommonClassNames.JAVA_LANG_STRING_BUFFER) || type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUILDER))) {
        return qualifierExpression;
      }
      else {
        return expression;
      }
    }
  }

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

  private static class StringEqualsEmptyStringVisitor extends BaseInspectionVisitor {

    @Override
    public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) {
      super.visitMethodCallExpression(call);
      final PsiReferenceExpression methodExpression = call.getMethodExpression();
      @NonNls final String methodName = methodExpression.getReferenceName();
      if (!"equals".equals(methodName)) {
        return;
      }
      final PsiExpressionList argumentList = call.getArgumentList();
      final PsiExpression[] arguments = argumentList.getExpressions();
      if (arguments.length != 1) {
        return;
      }
      final PsiElement context = call.getParent();
      final boolean useIsEmpty = PsiUtil.isLanguageLevel6OrHigher(call);
      if (!useIsEmpty && context instanceof PsiExpressionStatement) {
        // cheesy, but necessary, because otherwise the quickfix will
        // produce uncompilable code (out of merely incorrect code).
        return;
      }

      final PsiExpression qualifier = methodExpression.getQualifierExpression();
      final PsiExpression argument = arguments[0];
      if (ExpressionUtils.isEmptyStringLiteral(qualifier)) {
        final PsiType type = argument.getType();
        if (!TypeUtils.isJavaLangString(type)) {
          return;
        }
      }
      else if (ExpressionUtils.isEmptyStringLiteral(argument)) {
        if (qualifier == null) {
          return;
        }
        final PsiType type = qualifier.getType();
        if (!TypeUtils.isJavaLangString(type)) {
          return;
        }
      }
      else {
        return;
      }
      registerMethodCallError(call, Boolean.valueOf(useIsEmpty));
    }
  }
}