Search in sources :

Example 1 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GroovyReferenceCopyPasteProcessor method findReferencesToRestore.

@NotNull
@Override
protected GrReferenceElement[] findReferencesToRestore(PsiFile file, RangeMarker bounds, ReferenceData[] referenceData) {
    PsiManager manager = file.getManager();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    PsiResolveHelper helper = facade.getResolveHelper();
    GrReferenceElement[] refs = new GrReferenceElement[referenceData.length];
    for (int i = 0; i < referenceData.length; i++) {
        ReferenceData data = referenceData[i];
        PsiClass refClass = facade.findClass(data.qClassName, file.getResolveScope());
        if (refClass == null)
            continue;
        int startOffset = data.startOffset + bounds.getStartOffset();
        int endOffset = data.endOffset + bounds.getStartOffset();
        PsiElement element = file.findElementAt(startOffset);
        if (element != null && element.getParent() instanceof GrReferenceElement && !PsiUtil.isThisOrSuperRef(element.getParent())) {
            GrReferenceElement reference = (GrReferenceElement) element.getParent();
            TextRange range = reference.getTextRange();
            if (range.getStartOffset() == startOffset && range.getEndOffset() == endOffset) {
                if (data.staticMemberName == null) {
                    PsiClass refClass1 = helper.resolveReferencedClass(reference.getText(), reference);
                    if (refClass1 == null || !manager.areElementsEquivalent(refClass, refClass1)) {
                        refs[i] = reference;
                    }
                } else {
                    if (reference instanceof GrReferenceExpression) {
                        PsiElement referent = resolveReferenceIgnoreOverriding(reference);
                        if (!(referent instanceof PsiNamedElement) || !data.staticMemberName.equals(((PsiNamedElement) referent).getName()) || !(referent instanceof PsiMember) || ((PsiMember) referent).getContainingClass() == null || !data.qClassName.equals(((PsiMember) referent).getContainingClass().getQualifiedName())) {
                            refs[i] = reference;
                        }
                    }
                }
            }
        }
    }
    return refs;
}
Also used : TextRange(com.intellij.openapi.util.TextRange) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) ReferenceData(com.intellij.codeInsight.editorActions.ReferenceData) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GrPullUpConflictsUtil method checkConflicts.

public static MultiMap<PsiElement, String> checkConflicts(final MemberInfoBase<? extends GrMember>[] infos, @NotNull final PsiClass subclass, @Nullable PsiClass superClass, @NotNull final PsiPackage targetPackage, @NotNull PsiDirectory targetDirectory, final InterfaceContainmentVerifier interfaceContainmentVerifier, boolean movedMembers2Super) {
    final PsiElement targetRepresentativeElement;
    final boolean isInterfaceTarget;
    if (superClass != null) {
        isInterfaceTarget = superClass.isInterface();
        targetRepresentativeElement = superClass;
    } else {
        isInterfaceTarget = false;
        targetRepresentativeElement = targetDirectory;
    }
    final Set<GrMember> movedMembers = ContainerUtil.newHashSet();
    final Set<GrMethod> abstractMethods = ContainerUtil.newHashSet();
    for (MemberInfoBase<? extends GrMember> info : infos) {
        GrMember member = info.getMember();
        if (member instanceof GrMethod) {
            if (!info.isToAbstract() && !isInterfaceTarget) {
                movedMembers.add(member);
            } else {
                abstractMethods.add((GrMethod) member);
            }
        } else {
            movedMembers.add(member);
        }
    }
    final Set<PsiMethod> allAbstractMethods = new HashSet<>(abstractMethods);
    if (superClass != null) {
        for (PsiMethod method : subclass.getMethods()) {
            if (!movedMembers.contains(method) && !method.hasModifierProperty(PsiModifier.PRIVATE)) {
                if (method.findSuperMethods(superClass).length > 0) {
                    allAbstractMethods.add(method);
                }
            }
        }
    }
    final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    GrRefactoringConflictsUtil.analyzeAccessibilityConflicts(movedMembers, superClass, conflicts, VisibilityUtil.ESCALATE_VISIBILITY, targetRepresentativeElement, allAbstractMethods);
    if (superClass != null) {
        if (movedMembers2Super) {
            checkSuperclassMembers(superClass, infos, conflicts);
            if (isInterfaceTarget) {
                checkInterfaceTarget(infos, conflicts);
            }
        } else {
            final String qualifiedName = superClass.getQualifiedName();
            assert qualifiedName != null;
            if (superClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
                if (!Comparing.strEqual(StringUtil.getPackageName(qualifiedName), targetPackage.getQualifiedName())) {
                    conflicts.putValue(superClass, RefactoringUIUtil.getDescription(superClass, true) + " won't be accessible from " + RefactoringUIUtil.getDescription(targetPackage, true));
                }
            }
        }
    }
    // check if moved methods use other members in the classes between Subclass and Superclass
    List<PsiElement> checkModuleConflictsList = new ArrayList<>();
    for (PsiMember member : movedMembers) {
        if (member instanceof PsiMethod || member instanceof PsiClass && !(member instanceof PsiCompiledElement)) {
            GrClassMemberReferenceVisitor visitor = movedMembers2Super ? new ConflictingUsagesOfSubClassMembers(member, movedMembers, abstractMethods, subclass, superClass, superClass != null ? null : targetPackage, conflicts, interfaceContainmentVerifier) : new ConflictingUsagesOfSuperClassMembers(member, subclass, targetPackage, movedMembers, conflicts);
            ((GroovyPsiElement) member).accept(visitor);
        }
        checkModuleConflictsList.add(member);
    }
    for (final PsiMethod method : abstractMethods) {
        ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getParameterList());
        ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getReturnTypeElement());
        ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getTypeParameterList());
    }
    GrRefactoringConflictsUtil.analyzeModuleConflicts(subclass.getProject(), checkModuleConflictsList, UsageInfo.EMPTY_ARRAY, targetRepresentativeElement, conflicts);
    final String fqName = subclass.getQualifiedName();
    final String packageName;
    if (fqName != null) {
        packageName = StringUtil.getPackageName(fqName);
    } else {
        final PsiFile psiFile = PsiTreeUtil.getParentOfType(subclass, PsiFile.class);
        if (psiFile instanceof PsiClassOwner) {
            packageName = ((PsiClassOwner) psiFile).getPackageName();
        } else {
            packageName = null;
        }
    }
    final boolean toDifferentPackage = !Comparing.strEqual(targetPackage.getQualifiedName(), packageName);
    for (final GrMethod abstractMethod : abstractMethods) {
        abstractMethod.accept(new GrClassMemberReferenceVisitor(subclass) {

            @Override
            protected void visitClassMemberReferenceElement(GrMember classMember, GrReferenceElement classMemberReference) {
                if (classMember != null && willBeMoved(classMember, movedMembers)) {
                    boolean isAccessible = false;
                    if (classMember.hasModifierProperty(PsiModifier.PRIVATE)) {
                        isAccessible = true;
                    } else if (classMember.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && toDifferentPackage) {
                        isAccessible = true;
                    }
                    if (isAccessible) {
                        String message = RefactoringUIUtil.getDescription(abstractMethod, false) + " uses " + RefactoringUIUtil.getDescription(classMember, true) + " which won't be accessible from the subclass.";
                        message = CommonRefactoringUtil.capitalize(message);
                        conflicts.putValue(classMember, message);
                    }
                }
            }
        });
        if (abstractMethod.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && toDifferentPackage) {
            if (!isInterfaceTarget) {
                String message = "Can't make " + RefactoringUIUtil.getDescription(abstractMethod, false) + " abstract as it won't be accessible from the subclass.";
                message = CommonRefactoringUtil.capitalize(message);
                conflicts.putValue(abstractMethod, message);
            }
        }
    }
    return conflicts;
}
Also used : GrClassMemberReferenceVisitor(org.jetbrains.plugins.groovy.refactoring.classMembers.GrClassMemberReferenceVisitor) ArrayList(java.util.ArrayList) MultiMap(com.intellij.util.containers.MultiMap) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) HashSet(java.util.HashSet) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrMember(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)

Example 3 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GrAliasImportIntention method updateRefs.

private static void updateRefs(List<UsageInfo> usages, final String memberName, final GrImportStatement updatedImport) {
    if (updatedImport == null)
        return;
    final String name = ApplicationManager.getApplication().runReadAction(new Computable<String>() {

        @Nullable
        @Override
        public String compute() {
            return updatedImport.getImportedName();
        }
    });
    for (final UsageInfo usage : usages) {
        ApplicationManager.getApplication().runWriteAction(() -> {
            final PsiElement usageElement = usage.getElement();
            if (usageElement == null)
                return;
            if (usageElement.getParent() instanceof GrImportStatement)
                return;
            if (usageElement instanceof GrReferenceElement) {
                final GrReferenceElement ref = (GrReferenceElement) usageElement;
                final PsiElement qualifier = ref.getQualifier();
                if (qualifier == null) {
                    final String refName = ref.getReferenceName();
                    if (refName == null)
                        return;
                    if (memberName.equals(refName)) {
                        ref.handleElementRename(name);
                    } else if (refName.equals(GroovyPropertyUtils.getPropertyNameByAccessorName(memberName))) {
                        final String newPropName = GroovyPropertyUtils.getPropertyNameByAccessorName(name);
                        if (newPropName != null) {
                            ref.handleElementRename(newPropName);
                        } else {
                            ref.handleElementRename(name);
                        }
                    } else if (refName.equals(GroovyPropertyUtils.getGetterNameBoolean(memberName))) {
                        final String getterName = GroovyPropertyUtils.getGetterNameBoolean(name);
                        ref.handleElementRename(getterName);
                    } else if (refName.equals(GroovyPropertyUtils.getGetterNameNonBoolean(memberName))) {
                        final String getterName = GroovyPropertyUtils.getGetterNameNonBoolean(name);
                        ref.handleElementRename(getterName);
                    } else if (refName.equals(GroovyPropertyUtils.getSetterName(memberName))) {
                        final String getterName = GroovyPropertyUtils.getSetterName(name);
                        ref.handleElementRename(getterName);
                    }
                }
            }
        });
    }
}
Also used : GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) Nullable(org.jetbrains.annotations.Nullable) UsageInfo(com.intellij.usageView.UsageInfo) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)

Example 4 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class MoveGroovyClassHandler method preprocessUsages.

@Override
public void preprocessUsages(Collection<UsageInfo> results) {
    //remove all alias-imported usages from collection
    for (Iterator<UsageInfo> iterator = results.iterator(); iterator.hasNext(); ) {
        UsageInfo info = iterator.next();
        if (info == null) {
            LOG.debug("info==null");
            continue;
        }
        final PsiReference ref = info.getReference();
        if (ref == null)
            continue;
        final PsiElement element = ref.getElement();
        if (!(element instanceof GrReferenceElement))
            continue;
        final GroovyResolveResult resolveResult = ((GrReferenceElement) element).advancedResolve();
        final PsiElement context = resolveResult.getCurrentFileResolveContext();
        if (!(context instanceof GrImportStatement))
            continue;
        if (!((GrImportStatement) context).isAliasedImport())
            continue;
        iterator.remove();
    }
}
Also used : GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) UsageInfo(com.intellij.usageView.UsageInfo) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)

Example 5 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GrKindWeigher method weigh.

@Override
public Comparable weigh(@NotNull LookupElement element, @NotNull CompletionLocation location) {
    final PsiElement position = location.getCompletionParameters().getPosition();
    if (!(position.getContainingFile() instanceof GroovyFileBase))
        return null;
    Object o = element.getObject();
    if (o instanceof ResolveResult) {
        o = ((ResolveResult) o).getElement();
    }
    final PsiElement parent = position.getParent();
    final PsiElement qualifier = parent instanceof GrReferenceElement ? ((GrReferenceElement) parent).getQualifier() : null;
    if (qualifier == null) {
        if (o instanceof NamedArgumentDescriptor) {
            switch(((NamedArgumentDescriptor) o).getPriority()) {
                case ALWAYS_ON_TOP:
                    return NotQualifiedKind.onTop;
                case AS_LOCAL_VARIABLE:
                    return NotQualifiedKind.local;
                default:
                    return NotQualifiedKind.unknown;
            }
        }
        if (o instanceof PsiVariable && !(o instanceof PsiField)) {
            return NotQualifiedKind.local;
        }
        PsiTypeLookupItem item = element.as(PsiTypeLookupItem.CLASS_CONDITION_KEY);
        if (item != null && item.getBracketsCount() > 0) {
            return NotQualifiedKind.arrayType;
        }
        if (isPriorityKeyword(o))
            return NotQualifiedKind.local;
        if (isLightElement(o))
            return NotQualifiedKind.unknown;
        if (o instanceof PsiClass) {
            if (((PsiClass) o).isAnnotationType() && GrMainCompletionProvider.AFTER_AT.accepts(position)) {
                final GrAnnotation annotation = PsiTreeUtil.getParentOfType(position, GrAnnotation.class);
                if (annotation != null) {
                    PsiElement annoParent = annotation.getParent();
                    PsiElement ownerToUse = annoParent instanceof PsiModifierList ? annoParent.getParent() : annoParent;
                    PsiAnnotation.TargetType[] elementTypeFields = GrAnnotationImpl.getApplicableElementTypeFields(ownerToUse);
                    if (AnnotationTargetUtil.findAnnotationTarget((PsiClass) o, elementTypeFields) != null) {
                        return NotQualifiedKind.restrictedClass;
                    }
                }
            }
            if (GrMainCompletionProvider.IN_CATCH_TYPE.accepts(position) && InheritanceUtil.isInheritor((PsiClass) o, CommonClassNames.JAVA_LANG_THROWABLE)) {
                return NotQualifiedKind.restrictedClass;
            }
        }
        if (o instanceof PsiMember) {
            final PsiClass containingClass = ((PsiMember) o).getContainingClass();
            if (isAccessor((PsiMember) o))
                return NotQualifiedKind.accessor;
            if (o instanceof PsiClass && ((PsiClass) o).getContainingClass() == null || o instanceof PsiPackage)
                return NotQualifiedKind.unknown;
            if (o instanceof PsiClass)
                return NotQualifiedKind.innerClass;
            if (PsiTreeUtil.isContextAncestor(containingClass, position, false))
                return NotQualifiedKind.currentClassMember;
            return NotQualifiedKind.member;
        }
        return NotQualifiedKind.unknown;
    } else {
        if (o instanceof PsiEnumConstant)
            return QualifiedKind.enumConstant;
        if (isLightElement(o))
            return QualifiedKind.unknown;
        if (o instanceof PsiMember) {
            if (isTrashMethod((PsiMember) o))
                return QualifiedKind.unknown;
            if (isAccessor((PsiMember) o))
                return QualifiedKind.accessor;
            if (isQualifierClassMember((PsiMember) o, qualifier)) {
                return QualifiedKind.currentClassMember;
            }
            if (o instanceof PsiClass && ((PsiClass) o).getContainingClass() == null || o instanceof PsiPackage)
                return QualifiedKind.unknown;
            if (o instanceof PsiClass)
                return QualifiedKind.innerClass;
            return QualifiedKind.member;
        }
        return QualifiedKind.unknown;
    }
}
Also used : NamedArgumentDescriptor(org.jetbrains.plugins.groovy.extensions.NamedArgumentDescriptor) PsiTypeLookupItem(com.intellij.codeInsight.lookup.PsiTypeLookupItem) GroovyFileBase(org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase) GrAnnotation(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)

Aggregations

GrReferenceElement (org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)25 GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)10 GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)6 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)6 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)6 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)5 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)5 PsiElement (com.intellij.psi.PsiElement)4 IncorrectOperationException (com.intellij.util.IncorrectOperationException)4 NotNull (org.jetbrains.annotations.NotNull)4 GrCodeReferenceElement (org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement)4 Nullable (org.jetbrains.annotations.Nullable)3 GroovyFileBase (org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase)3 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)3 GrPackageDefinition (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition)3 ReferenceData (com.intellij.codeInsight.editorActions.ReferenceData)2 ASTNode (com.intellij.lang.ASTNode)2 Document (com.intellij.openapi.editor.Document)2 Project (com.intellij.openapi.project.Project)2 TextRange (com.intellij.openapi.util.TextRange)2