001    /*
002     * Copyright 2010-2013 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.jet.lang.resolve.kotlin;
018    
019    import com.intellij.ide.highlighter.JavaClassFileType;
020    import com.intellij.openapi.vfs.VirtualFile;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    import org.jetbrains.jet.lang.resolve.java.structure.JavaClass;
024    import org.jetbrains.jet.lang.resolve.java.structure.impl.JavaClassImpl;
025    import org.jetbrains.jet.lang.resolve.name.FqName;
026    
027    public abstract class VirtualFileKotlinClassFinder implements VirtualFileFinder {
028        @Nullable
029        @Override
030        public KotlinJvmBinaryClass findKotlinClass(@NotNull FqName fqName) {
031            VirtualFile file = findVirtualFileWithHeader(fqName);
032            return file == null ? null : KotlinBinaryClassCache.getKotlinBinaryClass(file);
033        }
034    
035        @Override
036        @Nullable
037        public KotlinJvmBinaryClass findKotlinClass(@NotNull JavaClass javaClass) {
038            VirtualFile file = ((JavaClassImpl) javaClass).getPsi().getContainingFile().getVirtualFile();
039            if (javaClass.getOuterClass() != null) {
040                // For nested classes we get a file of the containing class, to get the actual class file for A.B.C,
041                // we take the file for A, take its parent directory, then in this directory we look for A$B$C.class
042                file = file.getParent().findChild(classFileName(javaClass) + ".class");
043                assert file != null : "Virtual file not found for " + javaClass;
044            }
045    
046            if (file.getFileType() != JavaClassFileType.INSTANCE) return null;
047    
048            return KotlinBinaryClassCache.getKotlinBinaryClass(file);
049        }
050    
051        @NotNull
052        private static String classFileName(@NotNull JavaClass jClass) {
053            JavaClass outerClass = jClass.getOuterClass();
054            if (outerClass == null) return jClass.getName().asString();
055            return classFileName(outerClass) + "$" + jClass.getName().asString();
056        }
057    }