Search in sources :

Example 6 with MethodSignature

use of com.intellij.psi.util.MethodSignature in project intellij-community by JetBrains.

the class JavaFindUsagesHelper method addMethodsUsages.

private static boolean addMethodsUsages(@NotNull final PsiClass aClass, @NotNull final PsiManager manager, @NotNull final JavaClassFindUsagesOptions options, @NotNull final Processor<UsageInfo> processor) {
    if (options.isIncludeInherited) {
        final PsiMethod[] methods = ReadAction.compute(aClass::getAllMethods);
        for (int i = 0; i < methods.length; i++) {
            final PsiMethod method = methods[i];
            // filter overridden methods
            final int finalI = i;
            final PsiClass methodClass = ReadAction.compute(() -> {
                MethodSignature methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
                for (int j = 0; j < finalI; j++) {
                    if (methodSignature.equals(methods[j].getSignature(PsiSubstitutor.EMPTY)))
                        return null;
                }
                return method.getContainingClass();
            });
            if (methodClass == null)
                continue;
            boolean equivalent = ReadAction.compute(() -> manager.areElementsEquivalent(methodClass, aClass));
            if (equivalent) {
                if (!addElementUsages(method, options, processor))
                    return false;
            } else {
                MethodReferencesSearch.SearchParameters parameters = new MethodReferencesSearch.SearchParameters(method, options.searchScope, true, options.fastTrack);
                boolean success = MethodReferencesSearch.search(parameters).forEach(new PsiReferenceProcessorAdapter(reference -> {
                    addResultFromReference(reference, methodClass, manager, aClass, options, processor);
                    return true;
                }));
                if (!success)
                    return false;
            }
        }
    } else {
        PsiMethod[] methods = ReadAction.compute(aClass::getMethods);
        for (PsiMethod method : methods) {
            if (!addElementUsages(method, options, processor))
                return false;
        }
    }
    return true;
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) PsiMetaOwner(com.intellij.psi.meta.PsiMetaOwner) java.util(java.util) PsiElementProcessorAdapter(com.intellij.psi.search.PsiElementProcessorAdapter) PsiMetaData(com.intellij.psi.meta.PsiMetaData) UsageInfo(com.intellij.usageView.UsageInfo) NullableComputable(com.intellij.openapi.util.NullableComputable) SearchScope(com.intellij.psi.search.SearchScope) ContainerUtil(com.intellij.util.containers.ContainerUtil) FindBundle(com.intellij.find.FindBundle) ReadAction(com.intellij.openapi.application.ReadAction) ReadActionProcessor(com.intellij.openapi.application.ReadActionProcessor) Comparing(com.intellij.openapi.util.Comparing) PomService(com.intellij.pom.references.PomService) PsiUtil(com.intellij.psi.util.PsiUtil) XmlAttributeValue(com.intellij.psi.xml.XmlAttributeValue) Logger(com.intellij.openapi.diagnostic.Logger) PomTarget(com.intellij.pom.PomTarget) Extensions(com.intellij.openapi.extensions.Extensions) ProgressManager(com.intellij.openapi.progress.ProgressManager) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) TextRange(com.intellij.openapi.util.TextRange) AliasingPsiTargetMapper(com.intellij.psi.targets.AliasingPsiTargetMapper) com.intellij.psi.search.searches(com.intellij.psi.search.searches) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) AliasingPsiTarget(com.intellij.psi.targets.AliasingPsiTarget) MethodSignature(com.intellij.psi.util.MethodSignature) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) ThrowSearchUtil(com.intellij.psi.impl.search.ThrowSearchUtil) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) PsiReferenceProcessorAdapter(com.intellij.psi.search.PsiReferenceProcessorAdapter) MethodSignature(com.intellij.psi.util.MethodSignature) PsiReferenceProcessorAdapter(com.intellij.psi.search.PsiReferenceProcessorAdapter)

Example 7 with MethodSignature

use of com.intellij.psi.util.MethodSignature in project intellij-community by JetBrains.

the class ConflictsUtil method checkMethodConflicts.

public static void checkMethodConflicts(@Nullable PsiClass aClass, @Nullable PsiMethod refactoredMethod, final PsiMethod prototype, final MultiMap<PsiElement, String> conflicts) {
    if (prototype == null)
        return;
    String protoMethodInfo = getMethodPrototypeString(prototype);
    PsiMethod method = aClass != null ? aClass.findMethodBySignature(prototype, true) : null;
    if (method == null && aClass != null) {
        final MethodSignature signature = prototype.getSignature(PsiSubstitutor.EMPTY);
        for (PsiMethod classMethod : aClass.getMethods()) {
            if (MethodSignatureUtil.areSignaturesErasureEqual(signature, classMethod.getSignature(PsiSubstitutor.EMPTY))) {
                method = classMethod;
                protoMethodInfo = "with same erasure";
                break;
            }
        }
    }
    if (method != null && method != refactoredMethod && !isStaticInterfaceMethods(aClass, refactoredMethod, method)) {
        if (aClass.equals(method.getContainingClass())) {
            final String classDescr = aClass instanceof PsiAnonymousClass ? RefactoringBundle.message("current.class") : RefactoringUIUtil.getDescription(aClass, false);
            conflicts.putValue(method, RefactoringBundle.message("method.0.is.already.defined.in.the.1", protoMethodInfo, classDescr));
        } else {
            // method somewhere in base class
            if (JavaPsiFacade.getInstance(method.getProject()).getResolveHelper().isAccessible(method, aClass, null)) {
                String className = CommonRefactoringUtil.htmlEmphasize(DescriptiveNameUtil.getDescriptiveName(method.getContainingClass()));
                if (PsiUtil.getAccessLevel(prototype.getModifierList()) >= PsiUtil.getAccessLevel(method.getModifierList())) {
                    boolean isMethodAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
                    boolean isMyMethodAbstract = refactoredMethod != null && refactoredMethod.hasModifierProperty(PsiModifier.ABSTRACT);
                    final String conflict = isMethodAbstract != isMyMethodAbstract ? RefactoringBundle.message("method.0.will.implement.method.of.the.base.class", protoMethodInfo, className) : RefactoringBundle.message("method.0.will.override.a.method.of.the.base.class", protoMethodInfo, className);
                    conflicts.putValue(method, conflict);
                } else {
                    // prototype is private, will be compile-error
                    conflicts.putValue(method, RefactoringBundle.message("method.0.will.hide.method.of.the.base.class", protoMethodInfo, className));
                }
            }
        }
    }
    if (aClass != null && prototype.hasModifierProperty(PsiModifier.PRIVATE)) {
        ClassInheritorsSearch.search(aClass).forEach(aClass1 -> {
            final PsiMethod[] methods = aClass1.findMethodsBySignature(prototype, false);
            for (PsiMethod method1 : methods) {
                conflicts.putValue(method1, "Method " + RefactoringUIUtil.getDescription(method1, true) + " will override method of the base class " + RefactoringUIUtil.getDescription(aClass1, false));
            }
            return true;
        });
    }
}
Also used : MethodSignature(com.intellij.psi.util.MethodSignature)

Example 8 with MethodSignature

use of com.intellij.psi.util.MethodSignature in project intellij-community by JetBrains.

the class GenerateEqualsHelper method createEquals.

private PsiMethod createEquals() throws IncorrectOperationException {
    @NonNls StringBuilder buffer = new StringBuilder();
    CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(myProject);
    ArrayList<PsiField> equalsFields = new ArrayList<>();
    ContainerUtil.addAll(equalsFields, myEqualsFields);
    Collections.sort(equalsFields, EqualsFieldsComparator.INSTANCE);
    final HashMap<String, Object> contextMap = new HashMap<>();
    final PsiType classType = JavaPsiFacade.getElementFactory(myClass.getProject()).createType(myClass);
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(myClass.getProject());
    String[] nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, classType).names;
    String instanceBaseName = nameSuggestions.length > 0 && nameSuggestions[0].length() < 10 ? nameSuggestions[0] : "that";
    contextMap.put(INSTANCE_NAME, instanceBaseName);
    final PsiType objectType = PsiType.getJavaLangObject(myClass.getManager(), myClass.getResolveScope());
    nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, objectType).names;
    final String objectBaseName = nameSuggestions.length > 0 ? nameSuggestions[0] : "object";
    contextMap.put(BASE_PARAM_NAME, objectBaseName);
    final MethodSignature equalsSignature = getEqualsSignature(myProject, myClass.getResolveScope());
    PsiMethod superEquals = MethodSignatureUtil.findMethodBySignature(myClass, equalsSignature, true);
    if (superEquals != null) {
        contextMap.put(SUPER_PARAM_NAME, superEquals.getParameterList().getParameters()[0].getName());
    }
    contextMap.put(SUPER_HAS_EQUALS, superMethodExists(equalsSignature));
    contextMap.put(CHECK_PARAMETER_WITH_INSTANCEOF, myCheckParameterWithInstanceof);
    final String methodText = GenerationUtil.velocityGenerateCode(myClass, equalsFields, myNonNullSet, new HashMap<>(), contextMap, EqualsHashCodeTemplatesManager.getInstance().getDefaultEqualsTemplate().getTemplate(), 0, false, myUseAccessors);
    buffer.append(methodText);
    PsiMethod result;
    try {
        result = myFactory.createMethodFromText(buffer.toString(), myClass);
    } catch (IncorrectOperationException e) {
        return null;
    }
    final PsiParameter[] parameters = result.getParameterList().getParameters();
    if (parameters.length != 1)
        return null;
    final PsiParameter parameter = parameters[0];
    PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, styleSettings.GENERATE_FINAL_PARAMETERS);
    PsiMethod method = (PsiMethod) myCodeStyleManager.reformat(result);
    if (superEquals != null) {
        OverrideImplementUtil.annotateOnOverrideImplement(method, myClass, superEquals);
    }
    method = (PsiMethod) myJavaCodeStyleManager.shortenClassReferences(method);
    return method;
}
Also used : NonNls(org.jetbrains.annotations.NonNls) MethodSignature(com.intellij.psi.util.MethodSignature) HashMap(com.intellij.util.containers.HashMap) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 9 with MethodSignature

use of com.intellij.psi.util.MethodSignature in project intellij-community by JetBrains.

the class ExtractSuperClassUtil method extractSuperClass.

public static PsiClass extractSuperClass(final Project project, final PsiDirectory targetDirectory, final String superclassName, final PsiClass subclass, final MemberInfo[] selectedMemberInfos, final DocCommentPolicy javaDocPolicy) throws IncorrectOperationException {
    project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_EXTRACT_SUPER_ID, createBeforeData(subclass, selectedMemberInfos));
    final PsiClass superclass = JavaDirectoryService.getInstance().createClass(targetDirectory, superclassName);
    try {
        final PsiModifierList superClassModifierList = superclass.getModifierList();
        assert superClassModifierList != null;
        superClassModifierList.setModifierProperty(PsiModifier.FINAL, false);
        final PsiReferenceList subClassExtends = subclass.getExtendsList();
        if (subClassExtends != null) {
            copyPsiReferenceList(subClassExtends, superclass.getExtendsList());
        } else if (subclass instanceof PsiAnonymousClass) {
            PsiJavaCodeReferenceElement classReference = ((PsiAnonymousClass) subclass).getBaseClassReference();
            PsiElement baseClass = classReference.resolve();
            if (baseClass instanceof PsiClass && ((PsiClass) baseClass).isInterface()) {
                superclass.getImplementsList().add(classReference);
            } else {
                superclass.getExtendsList().add(classReference);
            }
        }
        // create constructors if neccesary
        PsiMethod[] constructors = getCalledBaseConstructors(subclass);
        if (constructors.length > 0) {
            createConstructorsByPattern(project, superclass, constructors);
        }
        // clear original class' "extends" list
        if (subClassExtends != null) {
            clearPsiReferenceList(subclass.getExtendsList());
        }
        // make original class extend extracted superclass
        PsiJavaCodeReferenceElement ref = createExtendingReference(superclass, subclass, selectedMemberInfos);
        final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
        if (subClassExtends != null) {
            codeStyleManager.reformat(subclass.getExtendsList().add(ref));
        } else if (subclass instanceof PsiAnonymousClass) {
            codeStyleManager.reformat(((PsiAnonymousClass) subclass).getBaseClassReference().replace(ref));
        }
        PullUpProcessor pullUpHelper = new PullUpProcessor(subclass, superclass, selectedMemberInfos, javaDocPolicy);
        pullUpHelper.moveMembersToBase();
        pullUpHelper.moveFieldInitializations();
        Collection<MethodSignature> toImplement = OverrideImplementExploreUtil.getMethodSignaturesToImplement(superclass);
        if (!toImplement.isEmpty()) {
            superClassModifierList.setModifierProperty(PsiModifier.ABSTRACT, true);
        }
        return superclass;
    } finally {
        project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_EXTRACT_SUPER_ID, createAfterData(superclass));
    }
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) MethodSignature(com.intellij.psi.util.MethodSignature) PullUpProcessor(com.intellij.refactoring.memberPullUp.PullUpProcessor)

Example 10 with MethodSignature

use of com.intellij.psi.util.MethodSignature in project intellij-community by JetBrains.

the class MethodTextOccurrenceProcessor method processInexactReference.

protected boolean processInexactReference(PsiReference ref, PsiElement refElement, PsiMethod method, Processor<PsiReference> consumer) {
    if (refElement instanceof PsiMethod) {
        PsiMethod refMethod = (PsiMethod) refElement;
        PsiClass refMethodClass = refMethod.getContainingClass();
        if (refMethodClass == null)
            return true;
        if (!refMethod.hasModifierProperty(PsiModifier.STATIC)) {
            PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(myContainingClass, refMethodClass, PsiSubstitutor.EMPTY);
            if (substitutor != null) {
                MethodSignature superSignature = method.getSignature(substitutor);
                MethodSignature refSignature = refMethod.getSignature(PsiSubstitutor.EMPTY);
                if (MethodSignatureUtil.isSubsignature(superSignature, refSignature)) {
                    if (!consumer.process(ref))
                        return false;
                }
            }
        }
        if (!myStrictSignatureSearch) {
            PsiManager manager = method.getManager();
            if (manager.areElementsEquivalent(refMethodClass, myContainingClass)) {
                if (!consumer.process(ref))
                    return false;
            }
        }
    }
    return true;
}
Also used : MethodSignature(com.intellij.psi.util.MethodSignature)

Aggregations

MethodSignature (com.intellij.psi.util.MethodSignature)31 Nullable (org.jetbrains.annotations.Nullable)8 NotNull (org.jetbrains.annotations.NotNull)7 ArrayList (java.util.ArrayList)5 Map (java.util.Map)4 com.intellij.psi (com.intellij.psi)3 List (java.util.List)3 GrClosureSignature (org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrClosureSignature)3 ApplicationManager (com.intellij.openapi.application.ApplicationManager)2 Logger (com.intellij.openapi.diagnostic.Logger)2 TextRange (com.intellij.openapi.util.TextRange)2 CandidateInfo (com.intellij.psi.infos.CandidateInfo)2 MethodCandidateInfo (com.intellij.psi.infos.MethodCandidateInfo)2 Processor (com.intellij.util.Processor)2 GrSignature (org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrSignature)2 GrClosureType (org.jetbrains.plugins.groovy.lang.psi.impl.GrClosureType)2 OverrideImplementExploreUtil (com.intellij.codeInsight.generation.OverrideImplementExploreUtil)1 RedundantLambdaCodeBlockInspection (com.intellij.codeInspection.RedundantLambdaCodeBlockInspection)1 FindBundle (com.intellij.find.FindBundle)1 InjectedLanguageManager (com.intellij.lang.injection.InjectedLanguageManager)1