summaryrefslogtreecommitdiff
path: root/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/redundancy/ElementOnlyUsedFromTestCodeInspection.java
blob: 7cb49d1bae5155fee2bb3678939ea746f6cb765d (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
/*
 * Copyright 2011 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.redundancy;

import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInsight.TestFrameworks;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.reference.*;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseGlobalInspection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ElementOnlyUsedFromTestCodeInspection
  extends BaseGlobalInspection {

  private static final Key<Boolean> ONLY_USED_FROM_TEST_CODE =
    Key.create("ONLY_USED_FROM_TEST_CODE");

  @NotNull
  @Override
  public String getDisplayName() {
    return InspectionGadgetsBundle.message(
      "element.only.used.from.test.code.display.name");
  }

  @Override
  @Nullable
  public RefGraphAnnotator getAnnotator(@NotNull RefManager refManager) {
    return new ElementOnlyUsedFromTestCodeAnnotator();
  }

  @Nullable
  @Override
  public CommonProblemDescriptor[] checkElement(
    @NotNull RefEntity refEntity, @NotNull AnalysisScope scope, @NotNull InspectionManager manager,
    @NotNull GlobalInspectionContext globalContext,
    @NotNull ProblemDescriptionsProcessor processor) {
    if (!isOnlyUsedFromTestCode(refEntity)) {
      return null;
    }
    if (!(refEntity instanceof RefJavaElement)) {
      return null;
    }
    final RefJavaElement javaElement = (RefJavaElement)refEntity;
    if (!javaElement.isReferenced()) {
      return null;
    }
    final PsiElement element = javaElement.getElement();
    if (element instanceof PsiClass) {
      final PsiClass aClass = (PsiClass)element;
      final PsiIdentifier identifier = aClass.getNameIdentifier();
      if (identifier == null) {
        return null;
      }
      return new CommonProblemDescriptor[]{
        manager.createProblemDescriptor(identifier,
                                        InspectionGadgetsBundle.message(
                                          "class.only.used.from.test.code.problem.descriptor"),
                                        true, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false)
      };
    }
    else if (element instanceof PsiMethod) {
      final PsiMethod method = (PsiMethod)element;
      final PsiIdentifier identifier = method.getNameIdentifier();
      if (identifier == null) {
        return null;
      }
      return new CommonProblemDescriptor[]{
        manager.createProblemDescriptor(identifier,
                                        InspectionGadgetsBundle.message(
                                          "method.only.used.from.test.code.problem.descriptor"),
                                        true, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false)
      };
    }
    else if (element instanceof PsiField) {
      final PsiField field = (PsiField)element;
      final PsiIdentifier identifier = field.getNameIdentifier();
      return new CommonProblemDescriptor[]{
        manager.createProblemDescriptor(identifier,
                                        InspectionGadgetsBundle.message(
                                          "field.only.used.from.test.code.problem.descriptor"),
                                        true, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false)
      };
    }
    return null;
  }

  private static boolean isInsideTestClass(@NotNull PsiElement e) {
    final PsiClass aClass = getTopLevelParentClass(e);
    return aClass != null && TestFrameworks.getInstance().isTestClass(aClass);
  }

  private static boolean isUnderTestSources(PsiElement e) {
    final ProjectRootManager rootManager =
      ProjectRootManager.getInstance(e.getProject());
    final VirtualFile file = e.getContainingFile().getVirtualFile();
    return file != null &&
           rootManager.getFileIndex().isInTestSourceContent(file);
  }

  @Nullable
  public static PsiClass getTopLevelParentClass(PsiElement e) {
    PsiClass result = null;
    PsiElement parent = e.getParent();
    while (parent != null && !(parent instanceof PsiFile)) {
      if (parent instanceof PsiClass) {
        result = (PsiClass)parent;
      }
      parent = parent.getParent();
    }
    return result;
  }

  private static boolean isOnlyUsedFromTestCode(RefEntity refElement) {
    final Boolean usedFromTestCode =
      refElement.getUserData(ONLY_USED_FROM_TEST_CODE);
    return usedFromTestCode != null && usedFromTestCode.booleanValue();
  }

  private static class ElementOnlyUsedFromTestCodeAnnotator
    extends RefGraphAnnotator {

    @Override
    public void onMarkReferenced(RefElement refWhat, RefElement refFrom,
                                 boolean referencedFromClassInitializer) {
      if (!(refWhat instanceof RefMethod) &&
          !(refWhat instanceof RefField) &&
          !(refWhat instanceof RefClass)) {
        return;
      }
      if (referencedFromClassInitializer ||
          refFrom instanceof RefImplicitConstructor) {
        return;
      }
      final PsiElement whatElement = refWhat.getElement();
      if (isInsideTestClass(whatElement) ||
          isUnderTestSources(whatElement)) {
        // test code itself is allowed to only be used from test code
        return;
      }
      if (refFrom instanceof RefMethod && refWhat instanceof RefClass) {
        final RefMethod method = (RefMethod)refFrom;
        if (method.isConstructor() &&
            method.getOwnerClass() == refWhat) {
          // don't count references to class from its own constructor
          return;
        }
      }
      final Boolean onlyUsedFromTestCode =
        refWhat.getUserData(ONLY_USED_FROM_TEST_CODE);
      if (onlyUsedFromTestCode == null) {
        refWhat.putUserData(ONLY_USED_FROM_TEST_CODE, Boolean.TRUE);
      }
      else if (!onlyUsedFromTestCode.booleanValue()) {
        return;
      }
      final PsiElement fromElement = refFrom.getElement();
      if (isInsideTestClass(fromElement) ||
          isUnderTestSources(fromElement)) {
        return;
      }

      if (refWhat instanceof RefMethod) {
        final RefMethod what = (RefMethod)refWhat;
        if (what.isConstructor()) {
          final RefClass ownerClass = what.getOwnerClass();
          ownerClass.putUserData(ONLY_USED_FROM_TEST_CODE,
                                 Boolean.FALSE);
          // do count references to class from its own constructor
          // when that constructor is used outside of test code.
        }
      }
      refWhat.putUserData(ONLY_USED_FROM_TEST_CODE, Boolean.FALSE);
    }
  }
}