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.cli.jvm.compiler;
018
019 import com.intellij.openapi.vfs.VirtualFile;
020 import org.jetbrains.annotations.NotNull;
021 import org.jetbrains.annotations.Nullable;
022 import org.jetbrains.jet.lang.resolve.kotlin.VirtualFileFinder;
023 import org.jetbrains.jet.lang.resolve.kotlin.VirtualFileKotlinClass;
024 import org.jetbrains.jet.lang.resolve.kotlin.header.KotlinClassHeader;
025 import org.jetbrains.jet.lang.resolve.name.FqName;
026
027 public class CliVirtualFileFinder implements VirtualFileFinder {
028
029 @NotNull
030 private final ClassPath classPath;
031
032 public CliVirtualFileFinder(@NotNull ClassPath path) {
033 classPath = path;
034 }
035
036 @Nullable
037 @Override
038 public VirtualFile find(@NotNull FqName className) {
039 for (VirtualFile root : classPath) {
040 VirtualFile fileInRoot = findFileInRoot(className.asString(), root);
041 if (fileInRoot != null) {
042 return fileInRoot;
043 }
044 }
045 return null;
046 }
047
048 //NOTE: copied with some changes from CoreJavaFileManager
049 @Nullable
050 private static VirtualFile findFileInRoot(@NotNull String qName, @NotNull VirtualFile root) {
051 String pathRest = qName;
052 VirtualFile cur = root;
053
054 while (true) {
055 int dot = pathRest.indexOf('.');
056 if (dot < 0) break;
057
058 String pathComponent = pathRest.substring(0, dot);
059 VirtualFile child = cur.findChild(pathComponent);
060
061 if (child == null) break;
062 pathRest = pathRest.substring(dot + 1);
063 cur = child;
064 }
065
066 String className = pathRest.replace('.', '$');
067 VirtualFile vFile = cur.findChild(className + ".class");
068 if (vFile != null) {
069 if (!vFile.isValid()) {
070 //TODO: log
071 return null;
072 }
073 //NOTE: currently we use VirtualFileFinder to find Kotlin binaries only
074 if (KotlinClassHeader.read(new VirtualFileKotlinClass(vFile)) != null) {
075 return vFile;
076 }
077 }
078 return null;
079 }
080 }