summaryrefslogtreecommitdiff
path: root/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ConvertSwitchToIfIntention.java
blob: 72df2025348fa506d479ece8d71ad86bd9946e77 (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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.intellij.psi.CommonClassNames.JAVA_LANG_STRING;

/**
* User: anna
* Date: 2/22/12
*/
public class ConvertSwitchToIfIntention implements IntentionAction {
  private final PsiSwitchStatement mySwitchExpression;

  public ConvertSwitchToIfIntention(@NotNull PsiSwitchStatement switchStatement) {
    mySwitchExpression = switchStatement;
  }

  @NotNull
  @Override
  public String getText() {
    return "Replace 'switch' with 'if'";
  }

  @NotNull
  @Override
  public String getFamilyName() {
    return getText();
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    final PsiCodeBlock body = mySwitchExpression.getBody();
    return body != null && body.getStatements().length > 0;
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    doProcessIntention(mySwitchExpression);
  }

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

  public static void doProcessIntention(@NotNull PsiSwitchStatement switchStatement) {
    final PsiExpression switchExpression = switchStatement.getExpression();
    if (switchExpression == null) {
      return;
    }
    final PsiType switchExpressionType = switchExpression.getType();
    if (switchExpressionType == null) {
      return;
    }
    final boolean isSwitchOnString =
      switchExpressionType.equalsToText(JAVA_LANG_STRING);
    boolean useEquals = isSwitchOnString;
    if (!useEquals) {
      final PsiClass aClass = PsiUtil.resolveClassInType(switchExpressionType);
      useEquals = aClass != null && !aClass.isEnum();
    }
    final String declarationString;
    final boolean hadSideEffects;
    final String expressionText;
    final Project project = switchStatement.getProject();
    if (RemoveUnusedVariableUtil.checkSideEffects(switchExpression, null, new ArrayList<PsiElement>())) {
      hadSideEffects = true;

      final JavaCodeStyleManager javaCodeStyleManager =
        JavaCodeStyleManager.getInstance(project);
      final String variableName;
      if (isSwitchOnString) {
        variableName = javaCodeStyleManager.suggestUniqueVariableName(
          "s", switchExpression, true);
      }
      else {
        variableName = javaCodeStyleManager.suggestUniqueVariableName(
          "i", switchExpression, true);
      }
      expressionText = variableName;
      declarationString =
        switchExpressionType.getPresentableText() + ' ' +
        variableName + " = " +
        switchExpression.getText() + ';';
    }
    else {
      hadSideEffects = false;
      declarationString = null;
      expressionText = switchExpression.getText();
    }
    final PsiCodeBlock body = switchStatement.getBody();
    if (body == null) {
      return;
    }
    final List<SwitchStatementBranch> openBranches =
      new ArrayList<SwitchStatementBranch>();
    final Set<PsiLocalVariable> declaredVariables =
      new HashSet<PsiLocalVariable>();
    final List<SwitchStatementBranch> allBranches =
      new ArrayList<SwitchStatementBranch>();
    SwitchStatementBranch currentBranch = null;
    final PsiElement[] children = body.getChildren();
    for (int i = 1; i < children.length - 1; i++) {
      final PsiElement statement = children[i];
      if (statement instanceof PsiSwitchLabelStatement) {
        final PsiSwitchLabelStatement label =
          (PsiSwitchLabelStatement)statement;
        if (currentBranch == null) {
          openBranches.clear();
          currentBranch = new SwitchStatementBranch();
          currentBranch.addPendingVariableDeclarations(declaredVariables);
          allBranches.add(currentBranch);
          openBranches.add(currentBranch);
        }
        else if (currentBranch.hasStatements()) {
          currentBranch = new SwitchStatementBranch();
          allBranches.add(currentBranch);
          openBranches.add(currentBranch);
        }
        if (label.isDefaultCase()) {
          currentBranch.setDefault();
        }
        else {
          final PsiExpression value = label.getCaseValue();
          final String valueText = getCaseValueText(value);
          currentBranch.addCaseValue(valueText);
        }
      }
      else {
        if (statement instanceof PsiStatement) {
          if (statement instanceof PsiDeclarationStatement) {
            final PsiDeclarationStatement declarationStatement =
              (PsiDeclarationStatement)statement;
            final PsiElement[] elements =
              declarationStatement.getDeclaredElements();
            for (PsiElement varElement : elements) {
              final PsiLocalVariable variable =
                (PsiLocalVariable)varElement;
              declaredVariables.add(variable);
            }
          }
          for (SwitchStatementBranch branch : openBranches) {
            branch.addStatement(statement);
          }
          try {
            ControlFlow controlFlow = ControlFlowFactory
                         .getInstance(project).getControlFlow(statement, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance());
            int startOffset = controlFlow.getStartOffset(statement);
            int endOffset = controlFlow.getEndOffset(statement);
            if (startOffset != -1 && endOffset != -1 && !ControlFlowUtil.canCompleteNormally(controlFlow, startOffset, endOffset)) {
              currentBranch = null;
            }
          }
          catch (AnalysisCanceledException e) {
            currentBranch = null;
          }
        }
        else {
          for (SwitchStatementBranch branch : openBranches) {
            if (statement instanceof PsiWhiteSpace) {
              branch.addWhiteSpace(statement);
            }
            else {
              branch.addComment(statement);
            }
          }
        }
      }
    }
    final StringBuilder ifStatementText = new StringBuilder();
    boolean firstBranch = true;
    SwitchStatementBranch defaultBranch = null;
    for (SwitchStatementBranch branch : allBranches) {
      if (branch.isDefault()) {
        defaultBranch = branch;
      }
      else {
        final List<String> caseValues = branch.getCaseValues();
        final List<PsiElement> bodyElements = branch.getBodyElements();
        final Set<PsiLocalVariable> pendingVariableDeclarations =
          branch.getPendingVariableDeclarations();
        dumpBranch(expressionText, caseValues, bodyElements,
                   pendingVariableDeclarations, firstBranch,
                   useEquals, ifStatementText);
        firstBranch = false;
      }
    }
    if (defaultBranch != null) {
      final List<PsiElement> bodyElements =
        defaultBranch.getBodyElements();
      final Set<PsiLocalVariable> pendingVariableDeclarations =
        defaultBranch.getPendingVariableDeclarations();
      dumpDefaultBranch(bodyElements, pendingVariableDeclarations,
                        firstBranch, ifStatementText);
    }
    if (ifStatementText.length() == 0) return;
    final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    final PsiElementFactory factory = psiFacade.getElementFactory();
    if (hadSideEffects) {
      final PsiStatement declarationStatement =
        factory.createStatementFromText(declarationString,
                                        switchStatement);
      final PsiStatement ifStatement =
        factory.createStatementFromText(ifStatementText.toString(),
                                        switchStatement);
      final PsiElement parent = switchStatement.getParent();
      parent.addBefore(declarationStatement, switchStatement);
      switchStatement.replace(ifStatement);
    }
    else {
      final PsiStatement newStatement =
        factory.createStatementFromText(ifStatementText.toString(),
                                        switchStatement);
      switchStatement.replace(newStatement);
    }
  }

  private static String getCaseValueText(PsiExpression value) {
    if (value == null) {
      return "";
    }
    if (value instanceof PsiParenthesizedExpression) {
      final PsiParenthesizedExpression parenthesizedExpression =
        (PsiParenthesizedExpression)value;
      final PsiExpression expression =
        parenthesizedExpression.getExpression();
      return getCaseValueText(expression);
    }
    if (!(value instanceof PsiReferenceExpression)) {
      return value.getText();
    }
    final PsiReferenceExpression referenceExpression =
      (PsiReferenceExpression)value;
    final PsiElement target = referenceExpression.resolve();
    final String text = referenceExpression.getText();
    if (!(target instanceof PsiEnumConstant)) {
      return value.getText();
    }
    final PsiEnumConstant enumConstant = (PsiEnumConstant)target;
    final PsiClass aClass = enumConstant.getContainingClass();
    if (aClass == null) {
      return value.getText();
    }
    final String name = aClass.getQualifiedName();
    return name + '.' + text;
  }

  private static void dumpBranch(
    String expressionText, List<String> caseValues,
    List<PsiElement> bodyStatements,
    Set<PsiLocalVariable> variables, boolean firstBranch,
    boolean useEquals,
    @NonNls StringBuilder ifStatementString) {
    if (!firstBranch) {
      ifStatementString.append("else ");
    }
    dumpCaseValues(expressionText, caseValues, useEquals,
                   ifStatementString);
    dumpBody(bodyStatements, variables, ifStatementString);
  }

  private static void dumpDefaultBranch(
    List<PsiElement> bodyStatements,
    Set<PsiLocalVariable> variables, boolean firstBranch,
    @NonNls StringBuilder ifStatementString) {
    if (!firstBranch) {
      ifStatementString.append("else ");
    }
    dumpBody(bodyStatements, variables, ifStatementString);
  }

  private static void dumpCaseValues(
    String expressionText, List<String> caseValues, boolean useEquals,
    @NonNls StringBuilder ifStatementString) {
    ifStatementString.append("if(");
    boolean firstCaseValue = true;
    for (String caseValue : caseValues) {
      if (!firstCaseValue) {
        ifStatementString.append("||");
      }
      firstCaseValue = false;
      ifStatementString.append(expressionText);
      if (useEquals) {
        ifStatementString.append(".equals(");
        ifStatementString.append(caseValue);
        ifStatementString.append(')');
      }
      else {
        ifStatementString.append("==");
        ifStatementString.append(caseValue);
      }
    }
    ifStatementString.append(')');
  }

  private static void dumpBody(List<PsiElement> bodyStatements,
                               Set<PsiLocalVariable> variables,
                               @NonNls StringBuilder ifStatementString) {
    ifStatementString.append('{');
    for (PsiLocalVariable variable : variables) {
      if (ReferencesSearch.search(variable, new LocalSearchScope(bodyStatements.toArray(new PsiElement[bodyStatements.size()]))).findFirst() != null) {
        final PsiType varType = variable.getType();
        ifStatementString.append(varType.getPresentableText());
        ifStatementString.append(' ');
        ifStatementString.append(variable.getName());
        ifStatementString.append(';');
      }
    }
    for (PsiElement bodyStatement : bodyStatements) {
      if (bodyStatement instanceof PsiBlockStatement) {
        final PsiBlockStatement blockStatement =
          (PsiBlockStatement)bodyStatement;
        final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
        final PsiStatement[] statements = codeBlock.getStatements();
        for (PsiStatement statement : statements) {
          appendElement(statement, ifStatementString);
        }
      }
      else {
        appendElement(bodyStatement, ifStatementString);
      }
    }
    ifStatementString.append("\n}");
  }

  private static void appendElement(
    PsiElement element, @NonNls StringBuilder ifStatementString) {
    if (element instanceof PsiBreakStatement) {
      final PsiBreakStatement breakStatement =
        (PsiBreakStatement)element;
      final PsiIdentifier identifier =
        breakStatement.getLabelIdentifier();
      if (identifier == null) {
        return;
      }
    }
    final String text = element.getText();
    ifStatementString.append(text);
  }
}