summaryrefslogtreecommitdiff
path: root/java/java-psi-impl/src/com/intellij/psi/NonClasspathClassFinder.java
blob: 59a4e10d40fe0f81e6b6d071bf47abbb1778ccdd (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
/*
 * 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.psi;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.impl.file.PsiPackageImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.NonClasspathDirectoriesScope;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author peter
 */
public abstract class NonClasspathClassFinder extends PsiElementFinder {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.NonClasspathClassFinder");
  private final AtomicLong myLastStamp = new AtomicLong();
  protected final Project myProject;
  private volatile List<VirtualFile> myCache;
  private final PsiManager myManager;
  private final String[] myFileExtensions;

  public NonClasspathClassFinder(Project project, String... fileExtensions) {
    myProject = project;
    myManager = PsiManager.getInstance(myProject);
    myFileExtensions = ArrayUtil.append(fileExtensions, "class");
  }

  protected List<VirtualFile> getClassRoots(@Nullable GlobalSearchScope scope) {
    return getClassRoots();
  }

  protected List<VirtualFile> getClassRoots() {
    List<VirtualFile> cache = myCache;
    long stamp = myManager.getModificationTracker().getModificationCount();
    if (myLastStamp.get() != stamp) {
      cache = null;
    }

    if (cache != null && !cache.isEmpty()) {
      for (VirtualFile file : cache) {
        if (!file.isValid()) {
          cache = null;
          break;
        }
      }
    }

    if (cache == null) {
      myCache = cache = calcClassRoots();
      myLastStamp.set(stamp);
    }
    return cache;
  }

  @Override
  public PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
    final List<VirtualFile> classRoots = getClassRoots(scope);
    if (classRoots.isEmpty()) {
      return null;
    }

    final String relPath = qualifiedName.replace('.', '/');
    for (final VirtualFile classRoot : classRoots) {
      if (scope.contains(classRoot)) {
        VirtualFile virtualFile = findFileByRelativePath(classRoot, relPath, myFileExtensions);
        if (virtualFile != null) {
          if (!virtualFile.isValid()) {
            LOG.error(
              "Invalid child of valid parent: " + virtualFile.getPath() + "; " + classRoot.isValid() + " path=" + classRoot.getPath());
            return null;
          }
          final PsiFile file = myManager.findFile(virtualFile);
          if (file instanceof PsiClassOwner) {
            final PsiClass[] classes = ((PsiClassOwner)file).getClasses();
            if (classes.length == 1) {
              return classes[0];
            }
          }
        }
      }
    }
    return null;
  }

  protected abstract List<VirtualFile> calcClassRoots();

  @NotNull
  @Override
  public PsiClass[] getClasses(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) {
    final List<VirtualFile> classRoots = getClassRoots(scope);
    if (classRoots.isEmpty()) {
      return PsiClass.EMPTY_ARRAY;
    }

    List<PsiClass> result = new ArrayList<PsiClass>();
    for (final VirtualFile classRoot : classRoots) {
      if (scope.contains(classRoot)) {
        final String pkgName = psiPackage.getQualifiedName();
        final VirtualFile dir = classRoot.findFileByRelativePath(pkgName.replace('.', '/'));
        if (dir != null && dir.isDirectory()) {
          for (final VirtualFile file : dir.getChildren()) {
            if (!file.isDirectory()) {
              final PsiFile psi = myManager.findFile(file);
              if (psi instanceof PsiClassOwner) {
                ContainerUtil.addAll(result, ((PsiClassOwner)psi).getClasses());
              }
            }
          }
        }
      }
    }
    return result.toArray(new PsiClass[result.size()]);
  }


  @NotNull
  @Override
  public Set<String> getClassNames(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) {
    final List<VirtualFile> classRoots = getClassRoots(scope);
    if (classRoots.isEmpty()) {
      return Collections.emptySet();
    }

    final Set<String> result = new HashSet<String>();
    for (final VirtualFile classRoot : classRoots) {
      if (scope.contains(classRoot)) {
        final String pkgName = psiPackage.getQualifiedName();
        final VirtualFile dir = classRoot.findFileByRelativePath(pkgName.replace('.', '/'));
        if (dir != null && dir.isDirectory()) {
          for (final VirtualFile file : dir.getChildren()) {
            if (!file.isDirectory() && ArrayUtil.contains(file.getExtension(), myFileExtensions)) {
              result.add(file.getNameWithoutExtension());
            }
          }
        }
      }
    }
    return result;
  }

  @Override
  public PsiPackage findPackage(@NotNull String qualifiedName) {
    final List<VirtualFile> classRoots = getClassRoots();
    if (classRoots.isEmpty()) {
      return null;
    }

    for (final VirtualFile classRoot : classRoots) {
      final VirtualFile dir = classRoot.findFileByRelativePath(qualifiedName.replace('.', '/'));
      if (dir != null && dir.isDirectory()) {
        return createPackage(qualifiedName);
      }
    }
    return null;
  }

  private PsiPackageImpl createPackage(String qualifiedName) {
    return new PsiPackageImpl(myManager, qualifiedName);
  }

  @Override
  public boolean processPackageDirectories(@NotNull PsiPackage psiPackage,
                                           @NotNull GlobalSearchScope scope,
                                           @NotNull Processor<PsiDirectory> consumer,
                                           boolean includeLibrarySources) {
    final List<VirtualFile> classRoots = getClassRoots(scope);
    if (classRoots.isEmpty()) {
      return true;
    }

    final String qname = psiPackage.getQualifiedName();
    final PsiManager psiManager = psiPackage.getManager();
    for (final VirtualFile classRoot : classRoots) {
      if (scope.contains(classRoot)) {
        final VirtualFile dir = classRoot.findFileByRelativePath(qname.replace('.', '/'));
        if (dir != null && dir.isDirectory()) {
          final PsiDirectory psiDirectory = ApplicationManager.getApplication().runReadAction(new Computable<PsiDirectory>() {
            @Override
            @Nullable
            public PsiDirectory compute() {
              return dir.isValid() ? psiManager.findDirectory(dir) : null;
            }
          });
          if (psiDirectory != null && !consumer.process(psiDirectory)) {
            return false;
          }
        }
      }
    }
    return true;
  }

  @NotNull
  @Override
  public PsiPackage[] getSubPackages(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) {
    final List<VirtualFile> classRoots = getClassRoots(scope);
    if (classRoots.isEmpty()) {
      return super.getSubPackages(psiPackage, scope);
    }

    List<PsiPackage> result = new ArrayList<PsiPackage>();
    for (final VirtualFile classRoot : classRoots) {
      if (scope.contains(classRoot)) {
        final String pkgName = psiPackage.getQualifiedName();
        final VirtualFile dir = classRoot.findFileByRelativePath(pkgName.replace('.', '/'));
        if (dir != null && dir.isDirectory()) {
          for (final VirtualFile file : dir.getChildren()) {
            if (file.isDirectory()) {
              result.add(createPackage(pkgName + "." + file.getName()));
            }
          }
        }
      }
    }
    return result.toArray(new PsiPackage[result.size()]);
  }

  @NotNull
  @Override
  public PsiClass[] findClasses(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
    final PsiClass psiClass = findClass(qualifiedName, scope);
    return psiClass == null ? PsiClass.EMPTY_ARRAY : new PsiClass[]{psiClass};
  }

  @NotNull
  public static GlobalSearchScope addNonClasspathScope(Project project, GlobalSearchScope base) {
    GlobalSearchScope scope = base;
    for (PsiElementFinder finder : Extensions.getExtensions(EP_NAME, project)) {
      if (finder instanceof NonClasspathClassFinder) {
        scope = scope.uniteWith(NonClasspathDirectoriesScope.compose(((NonClasspathClassFinder)finder).getClassRoots()));
      }
    }
    return scope;
  }

  public PsiManager getPsiManager() {
    return myManager;
  }

  @Nullable
  private static VirtualFile findFileByRelativePath(@NotNull VirtualFile root,
                                                    @NotNull String relPath,
                                                    @NotNull String[] extensions) {
    VirtualFile file = null;
    for (String extension : extensions) {
      file = root.findFileByRelativePath(relPath + '.' + extension);
      if (file != null) break;
    }
    return file;
  }
}