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.psi;
018
019 import com.intellij.psi.PsiElement;
020 import org.jetbrains.annotations.NotNull;
021 import org.jetbrains.annotations.Nullable;
022 import org.jetbrains.kotlin.name.FqName;
023 import org.jetbrains.kotlin.name.FqNameUnsafe;
024 import org.jetbrains.kotlin.name.Name;
025
026 public final class KtNamedDeclarationUtil {
027 @Nullable
028 public static FqNameUnsafe getUnsafeFQName(@NotNull KtNamedDeclaration namedDeclaration) {
029 FqName fqName = namedDeclaration.getFqName();
030 return fqName != null ? fqName.toUnsafe() : null;
031 }
032
033 @Nullable
034 //NOTE: use JetNamedDeclaration#getFqName instead
035 /*package private*/ static FqName getFQName(@NotNull KtNamedDeclaration namedDeclaration) {
036 Name name = namedDeclaration.getNameAsName();
037 if (name == null) {
038 return null;
039 }
040
041 FqName parentFqName = getParentFqName(namedDeclaration);
042
043 if (parentFqName == null) {
044 return null;
045 }
046
047 return parentFqName.child(name);
048 }
049
050 @Nullable
051 public static FqName getParentFqName(@NotNull KtNamedDeclaration namedDeclaration) {
052 PsiElement parent = namedDeclaration.getParent();
053 if (parent instanceof KtClassBody) {
054 // One nesting to JetClassBody doesn't affect to qualified name
055 parent = parent.getParent();
056 }
057
058 if (parent instanceof KtFile) {
059 return ((KtFile) parent).getPackageFqName();
060 }
061 else if (parent instanceof KtNamedFunction || parent instanceof KtClass) {
062 return getFQName((KtNamedDeclaration) parent);
063 }
064 else if (namedDeclaration instanceof KtParameter) {
065 KtClassOrObject constructorClass = KtPsiUtil.getClassIfParameterIsProperty((KtParameter) namedDeclaration);
066 if (constructorClass != null) {
067 return getFQName(constructorClass);
068 }
069 }
070 else if (parent instanceof KtObjectDeclaration) {
071 return getFQName((KtNamedDeclaration) parent);
072 }
073 return null;
074 }
075
076 private KtNamedDeclarationUtil() {
077 }
078 }