@Override
public PsiElement resolve(@NotNull PsiReference refElement, boolean incompleteCode) {
final PbRefImpl ref = (PbRefImpl) refElement;
final ReferenceKind refKind = ref.getRefKind();
final PbRef qualifier = ref.getQualifierRef();
switch (refKind) {
case FILE: {
//todo
final String relativePath = PbTextUtil.trim(ref.getText(),'\"');
if (relativePath.length() == 0) {
return null;
}
if (PbFileUtil.isPathToDirectory(relativePath)) {
return null;
}
final String fileName = new File(relativePath).getName();
//hack for test code
PsiFile psiFile = null;
PsiFile[] foundFiles = FilenameIndex.getFilesByName(ref.getProject(), fileName, ref.getResolveScope());
for (PsiFile foundFile : foundFiles) {
if (foundFile.getVirtualFile().getPath().equals(File.separator + relativePath)) {
psiFile = foundFile;
}
}
if (psiFile != null) return psiFile; //todo avoid such hacking
//real code
VirtualFile baseOfSearchPath;
if (ref.getNode().getElementType() == PbElementTypes.IMPORT_REF) {
baseOfSearchPath = ref.getContainingFile().getVirtualFile().getParent();
} else {
baseOfSearchPath = ref.getProject().getBaseDir();
}
VirtualFile vfile = baseOfSearchPath.findFileByRelativePath(relativePath);
if (vfile != null) {
return ref.getManager().findFile(vfile);
} else {
return null;
}
}
case PACKAGE: {
String qualifiedName = PbPsiUtil.getQualifiedReferenceText(ref);
JavaPsiFacade facade = JavaPsiFacade.getInstance(ref.getManager().getProject());
return facade.findPackage(qualifiedName);
}
case MESSAGE_OR_GROUP:
case MESSAGE_OR_ENUM_OR_GROUP:
case MESSAGE_OR_PACKAGE_OR_GROUP:
case EXTEND_FIELD: {
if (qualifier != null) { //foo.bar
final PsiElement resolvedElement = qualifier.resolve();
if (resolvedElement != null) {
return PbResolveUtil.resolveInScope(PbPsiUtil.getScope(resolvedElement), ref);
}
} else if (ref.findChildByType(DOT) != null) { //.foo
return PbResolveUtil.resolveInScope(PbPsiUtil.getRootScope(ref), ref);
} else { // foo
PsiElement upperScope = PbPsiUtil.getUpperScope(ref);
while (upperScope != null) {
PsiElement resolveResult = PbResolveUtil.resolveInScope(upperScope, ref);
if (resolveResult != null) {
return resolveResult;
}
upperScope = PbPsiUtil.getUpperScope(upperScope);
}
}
}
break;
case MESSAGE_OR_GROUP_FIELD: {
if (qualifier != null) {
final PsiElement resolvedElement = qualifier.resolve();
if (resolvedElement != null) {
return PbResolveUtil.resolveInScope(PbPsiUtil.getTypeScope(resolvedElement), ref);
}
}
}