001    /*
002     * Copyright 2010-2015 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.resolve.jvm;
018    
019    import com.intellij.openapi.components.ServiceManager;
020    import com.intellij.openapi.project.DumbAware;
021    import com.intellij.openapi.project.DumbService;
022    import com.intellij.openapi.project.Project;
023    import com.intellij.openapi.roots.PackageIndex;
024    import com.intellij.openapi.util.Pair;
025    import com.intellij.openapi.util.text.StringUtil;
026    import com.intellij.openapi.vfs.VirtualFile;
027    import com.intellij.psi.*;
028    import com.intellij.psi.impl.PsiElementFinderImpl;
029    import com.intellij.psi.impl.file.PsiPackageImpl;
030    import com.intellij.psi.impl.file.impl.JavaFileManager;
031    import com.intellij.psi.impl.light.LightModifierList;
032    import com.intellij.psi.search.GlobalSearchScope;
033    import com.intellij.psi.util.PsiModificationTracker;
034    import com.intellij.reference.SoftReference;
035    import com.intellij.util.CommonProcessors;
036    import com.intellij.util.ConcurrencyUtil;
037    import com.intellij.util.Query;
038    import com.intellij.util.containers.ContainerUtil;
039    import com.intellij.util.messages.MessageBus;
040    import kotlin.collections.ArraysKt;
041    import kotlin.collections.CollectionsKt;
042    import kotlin.jvm.functions.Function1;
043    import org.jetbrains.annotations.NotNull;
044    import org.jetbrains.annotations.Nullable;
045    import org.jetbrains.kotlin.idea.KotlinLanguage;
046    import org.jetbrains.kotlin.load.java.JavaClassFinderImpl;
047    import org.jetbrains.kotlin.name.FqName;
048    import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus;
049    import org.jetbrains.kotlin.name.ClassId;
050    
051    import java.util.ArrayList;
052    import java.util.Arrays;
053    import java.util.List;
054    import java.util.Set;
055    import java.util.concurrent.ConcurrentMap;
056    
057    public class KotlinJavaPsiFacade {
058        private volatile KotlinPsiElementFinderWrapper[] elementFinders;
059    
060        private static class PackageCache {
061            final ConcurrentMap<Pair<String, GlobalSearchScope>, PsiPackage> packageInScopeCache = ContainerUtil.newConcurrentMap();
062            final ConcurrentMap<String, Boolean> hasPackageInAllScopeCache = ContainerUtil.newConcurrentMap();
063        }
064    
065        private volatile SoftReference<PackageCache> packageCache;
066    
067        private final Project project;
068        private final LightModifierList emptyModifierList;
069    
070        public static KotlinJavaPsiFacade getInstance(Project project) {
071            return ServiceManager.getService(project, KotlinJavaPsiFacade.class);
072        }
073    
074        public KotlinJavaPsiFacade(@NotNull Project project) {
075            this.project = project;
076    
077            emptyModifierList = new LightModifierList(PsiManager.getInstance(project), KotlinLanguage.INSTANCE);
078    
079            final PsiModificationTracker modificationTracker = PsiManager.getInstance(project).getModificationTracker();
080            MessageBus bus = project.getMessageBus();
081    
082            bus.connect().subscribe(PsiModificationTracker.TOPIC, new PsiModificationTracker.Listener() {
083                private long lastTimeSeen = -1L;
084    
085                @Override
086                public void modificationCountChanged() {
087                    long now = modificationTracker.getJavaStructureModificationCount();
088                    if (lastTimeSeen != now) {
089                        lastTimeSeen = now;
090    
091                        packageCache = null;
092                    }
093                }
094            });
095        }
096    
097        public LightModifierList getEmptyModifierList() {
098            return emptyModifierList;
099        }
100    
101        public PsiClass findClass(@NotNull ClassId classId, @NotNull GlobalSearchScope scope) {
102            ProgressIndicatorAndCompilationCanceledStatus.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly
103    
104            String qualifiedName = classId.asSingleFqName().asString();
105    
106            if (shouldUseSlowResolve()) {
107                PsiClass[] classes = findClassesInDumbMode(qualifiedName, scope);
108                if (classes.length != 0) {
109                    return classes[0];
110                }
111                return null;
112            }
113    
114            for (KotlinPsiElementFinderWrapper finder : finders()) {
115                if (finder instanceof KotlinPsiElementFinderImpl) {
116                    PsiClass aClass = ((KotlinPsiElementFinderImpl) finder).findClass(classId, scope);
117                    if (aClass != null) return aClass;
118                }
119                else {
120                    PsiClass aClass = finder.findClass(qualifiedName, scope);
121                    if (aClass != null) {
122                        if (scope instanceof JavaClassFinderImpl.MyDelegatingGlobalSearchScope) {
123                            GlobalSearchScope baseScope = ((JavaClassFinderImpl.MyDelegatingGlobalSearchScope) scope).getBaseScope();
124                            boolean isSourcesScope = baseScope instanceof GlobalSearchScopeWithModuleSources;
125    
126                            if (!isSourcesScope) {
127                                Object originalFinder = (finder instanceof KotlinPsiElementFinderWrapperImpl)
128                                                        ? ((KotlinPsiElementFinderWrapperImpl) finder).getOriginal()
129                                                        : finder;
130    
131                                // Temporary fix for #KT-12402
132                                boolean isAndroidDataBindingClassWriter = originalFinder.getClass().getName()
133                                        .equals("com.android.tools.idea.databinding.DataBindingClassFinder");
134                                boolean isAndroidDataBindingComponentClassWriter = originalFinder.getClass().getName()
135                                        .equals("com.android.tools.idea.databinding.DataBindingComponentClassFinder");
136    
137                                if (isAndroidDataBindingClassWriter || isAndroidDataBindingComponentClassWriter) {
138                                    continue;
139                                }
140                            }
141                        }
142    
143                        return aClass;
144                    }
145                }
146            }
147    
148            return null;
149        }
150    
151        @Nullable
152        public Set<String> knownClassNamesInPackage(@NotNull FqName packageFqName) {
153            KotlinPsiElementFinderWrapper[] finders = finders();
154    
155            if (finders.length == 1) {
156                return ((KotlinPsiElementFinderImpl) finders[0]).knownClassNamesInPackage(packageFqName);
157            }
158    
159            return null;
160        }
161    
162        @NotNull
163        private PsiClass[] findClassesInDumbMode(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
164            String packageName = StringUtil.getPackageName(qualifiedName);
165            PsiPackage pkg = findPackage(packageName, scope);
166            String className = StringUtil.getShortName(qualifiedName);
167            if (pkg == null && packageName.length() < qualifiedName.length()) {
168                PsiClass[] containingClasses = findClassesInDumbMode(packageName, scope);
169                if (containingClasses.length == 1) {
170                    return PsiElementFinder.filterByName(className, containingClasses[0].getInnerClasses());
171                }
172    
173                return PsiClass.EMPTY_ARRAY;
174            }
175    
176            if (pkg == null || !pkg.containsClassNamed(className)) {
177                return PsiClass.EMPTY_ARRAY;
178            }
179    
180            return pkg.findClassByShortName(className, scope);
181        }
182    
183        private boolean shouldUseSlowResolve() {
184            DumbService dumbService = DumbService.getInstance(getProject());
185            return dumbService.isDumb() && dumbService.isAlternativeResolveEnabled();
186        }
187    
188        @NotNull
189        private KotlinPsiElementFinderWrapper[] finders() {
190            KotlinPsiElementFinderWrapper[] answer = elementFinders;
191            if (answer == null) {
192                answer = calcFinders();
193                elementFinders = answer;
194            }
195    
196            return answer;
197        }
198    
199        @NotNull
200        protected KotlinPsiElementFinderWrapper[] calcFinders() {
201            List<KotlinPsiElementFinderWrapper> elementFinders = new ArrayList<KotlinPsiElementFinderWrapper>();
202            elementFinders.add(new KotlinPsiElementFinderImpl(getProject()));
203    
204            List<PsiElementFinder> nonKotlinFinders = ArraysKt.filter(
205                    getProject().getExtensions(PsiElementFinder.EP_NAME), new Function1<PsiElementFinder, Boolean>() {
206                        @Override
207                        public Boolean invoke(PsiElementFinder finder) {
208                            return !(finder instanceof NonClasspathClassFinder || finder instanceof KotlinFinderMarker || finder instanceof PsiElementFinderImpl);
209                        }
210                    });
211    
212            elementFinders.addAll(CollectionsKt.map(nonKotlinFinders, new Function1<PsiElementFinder, KotlinPsiElementFinderWrapper>() {
213                @Override
214                public KotlinPsiElementFinderWrapper invoke(PsiElementFinder finder) {
215                    return wrap(finder);
216                }
217            }));
218    
219            return elementFinders.toArray(new KotlinPsiElementFinderWrapper[elementFinders.size()]);
220        }
221    
222        public PsiPackage findPackage(@NotNull String qualifiedName, GlobalSearchScope searchScope) {
223            PackageCache cache = SoftReference.dereference(packageCache);
224            if (cache == null) {
225                packageCache = new SoftReference<PackageCache>(cache = new PackageCache());
226            }
227    
228            Pair<String, GlobalSearchScope> key = new Pair<String, GlobalSearchScope>(qualifiedName, searchScope);
229            PsiPackage aPackage = cache.packageInScopeCache.get(key);
230            if (aPackage != null) {
231                return aPackage;
232            }
233    
234            KotlinPsiElementFinderWrapper[] finders = filteredFinders();
235    
236            Boolean packageFoundInAllScope = cache.hasPackageInAllScopeCache.get(qualifiedName);
237            if (packageFoundInAllScope != null) {
238                if (!packageFoundInAllScope.booleanValue()) return null;
239    
240                // Package was found in AllScope with some of finders but is absent in packageCache for current scope.
241                // We check only finders that depend on scope.
242                for (KotlinPsiElementFinderWrapper finder : finders) {
243                    if (!finder.isSameResultForAnyScope()) {
244                        aPackage = finder.findPackage(qualifiedName, searchScope);
245                        if (aPackage != null) {
246                            return ConcurrencyUtil.cacheOrGet(cache.packageInScopeCache, key, aPackage);
247                        }
248                    }
249                }
250            }
251            else {
252                for (KotlinPsiElementFinderWrapper finder : finders) {
253                    aPackage = finder.findPackage(qualifiedName, searchScope);
254    
255                    if (aPackage != null) {
256                        return ConcurrencyUtil.cacheOrGet(cache.packageInScopeCache, key, aPackage);
257                    }
258                }
259    
260                boolean found = false;
261                for (KotlinPsiElementFinderWrapper finder : finders) {
262                    if (!finder.isSameResultForAnyScope()) {
263                        aPackage = finder.findPackage(qualifiedName, GlobalSearchScope.allScope(project));
264                        if (aPackage != null) {
265                            found = true;
266                            break;
267                        }
268                    }
269                }
270    
271                cache.hasPackageInAllScopeCache.put(qualifiedName, found);
272            }
273    
274            return null;
275        }
276    
277        @NotNull
278        private KotlinPsiElementFinderWrapper[] filteredFinders() {
279            DumbService dumbService = DumbService.getInstance(getProject());
280            KotlinPsiElementFinderWrapper[] finders = finders();
281            if (dumbService.isDumb()) {
282                List<KotlinPsiElementFinderWrapper> list = dumbService.filterByDumbAwareness(Arrays.asList(finders));
283                finders = list.toArray(new KotlinPsiElementFinderWrapper[list.size()]);
284            }
285            return finders;
286        }
287    
288        @NotNull
289        public Project getProject() {
290            return project;
291        }
292    
293        public static KotlinPsiElementFinderWrapper wrap(PsiElementFinder finder) {
294            return finder instanceof DumbAware
295                   ? new KotlinPsiElementFinderWrapperImplDumbAware(finder)
296                   : new KotlinPsiElementFinderWrapperImpl(finder);
297        }
298    
299        interface KotlinPsiElementFinderWrapper {
300            PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope);
301            PsiPackage findPackage(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope);
302            boolean isSameResultForAnyScope();
303        }
304    
305        private static class KotlinPsiElementFinderWrapperImpl implements KotlinPsiElementFinderWrapper {
306            private final PsiElementFinder finder;
307    
308            private KotlinPsiElementFinderWrapperImpl(@NotNull PsiElementFinder finder) {
309                this.finder = finder;
310            }
311    
312            public PsiElementFinder getOriginal() {
313                return finder;
314            }
315    
316            @Override
317            public PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
318                return finder.findClass(qualifiedName, scope);
319            }
320    
321            @Override
322            public PsiPackage findPackage(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
323                // Original element finder can't search packages with scope
324                return finder.findPackage(qualifiedName);
325            }
326    
327            @Override
328            public boolean isSameResultForAnyScope() {
329                return true;
330            }
331    
332            @Override
333            public String toString() {
334                return finder.toString();
335            }
336        }
337    
338        private static class KotlinPsiElementFinderWrapperImplDumbAware extends KotlinPsiElementFinderWrapperImpl implements DumbAware {
339            private KotlinPsiElementFinderWrapperImplDumbAware(PsiElementFinder finder) {
340                super(finder);
341            }
342        }
343    
344        static class KotlinPsiElementFinderImpl implements KotlinPsiElementFinderWrapper, DumbAware {
345            private final JavaFileManager javaFileManager;
346            private final boolean isCliFileManager;
347    
348            private final PsiManager psiManager;
349            private final PackageIndex packageIndex;
350    
351            public KotlinPsiElementFinderImpl(Project project) {
352                this.javaFileManager = findJavaFileManager(project);
353                this.isCliFileManager = javaFileManager instanceof KotlinCliJavaFileManager;
354    
355                this.packageIndex = PackageIndex.getInstance(project);
356                this.psiManager = PsiManager.getInstance(project);
357            }
358    
359            @NotNull
360            private static JavaFileManager findJavaFileManager(@NotNull Project project) {
361                JavaFileManager javaFileManager = ServiceManager.getService(project, JavaFileManager.class);
362                if (javaFileManager == null) {
363                    throw new IllegalStateException("JavaFileManager component is not found in project");
364                }
365    
366                return javaFileManager;
367            }
368    
369    
370            @Override
371            public PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
372                return javaFileManager.findClass(qualifiedName, scope);
373            }
374    
375            public PsiClass findClass(@NotNull ClassId classId, @NotNull GlobalSearchScope scope) {
376                if (isCliFileManager) {
377                    return ((KotlinCliJavaFileManager) javaFileManager).findClass(classId, scope);
378                }
379                return findClass(classId.asSingleFqName().asString(), scope);
380            }
381    
382            @Nullable
383            public Set<String> knownClassNamesInPackage(@NotNull FqName packageFqName) {
384                if (isCliFileManager) {
385                    return ((KotlinCliJavaFileManager) javaFileManager).knownClassNamesInPackage(packageFqName);
386                }
387    
388                return null;
389            }
390    
391            @Override
392            public PsiPackage findPackage(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
393                if (isCliFileManager) {
394                    return javaFileManager.findPackage(qualifiedName);
395                }
396    
397                Query<VirtualFile> dirs = packageIndex.getDirsByPackageName(qualifiedName, true);
398                return hasDirectoriesInScope(dirs, scope) ? new PsiPackageImpl(psiManager, qualifiedName) : null;
399            }
400    
401            @Override
402            public boolean isSameResultForAnyScope() {
403                return false;
404            }
405    
406            private static boolean hasDirectoriesInScope(Query<VirtualFile> dirs, final GlobalSearchScope scope) {
407                CommonProcessors.FindProcessor<VirtualFile> findProcessor = new CommonProcessors.FindProcessor<VirtualFile>() {
408                    @Override
409                    protected boolean accept(VirtualFile file) {
410                        return scope.accept(file);
411                    }
412                };
413    
414                dirs.forEach(findProcessor);
415                return findProcessor.isFound();
416            }
417        }
418    }