Search in sources :

Example 1 with PsiImmediateClassType

use of com.intellij.psi.impl.source.PsiImmediateClassType in project intellij-community by JetBrains.

the class MethodsChainsCompletionContributor method searchForLookups.

private static List<LookupElement> searchForLookups(final TargetType target, final Set<String> contextRelevantTypes, final ChainCompletionContext completionContext) {
    final Project project = completionContext.getProject();
    final MethodsUsageIndexReader methodsUsageIndexReader = MethodsUsageIndexReader.getInstance(project);
    final List<MethodsChain> searchResult = searchChains(target, contextRelevantTypes, MAX_SEARCH_RESULT_SIZE, MAX_CHAIN_SIZE, completionContext, methodsUsageIndexReader);
    if (searchResult.size() < MAX_SEARCH_RESULT_SIZE) {
        if (!target.isArray()) {
            final List<MethodsChain> inheritorFilteredSearchResult = new SmartList<>();
            final Processor<TargetType> consumer = targetType -> {
                for (final MethodsChain chain : searchChains(targetType, contextRelevantTypes, MAX_SEARCH_RESULT_SIZE, MAX_CHAIN_SIZE, completionContext, methodsUsageIndexReader)) {
                    boolean insert = true;
                    for (final MethodsChain baseChain : searchResult) {
                        final MethodsChain.CompareResult r = MethodsChain.compare(baseChain, chain, completionContext.getPsiManager());
                        if (r != MethodsChain.CompareResult.NOT_EQUAL) {
                            insert = false;
                            break;
                        }
                    }
                    if (insert) {
                        inheritorFilteredSearchResult.add(chain);
                    }
                }
                searchResult.addAll(inheritorFilteredSearchResult);
                return searchResult.size() < MAX_SEARCH_RESULT_SIZE;
            };
            DirectClassInheritorsSearch.search(((PsiClassType) target.getPsiType()).resolve()).forEach(psiClass -> {
                final String inheritorQName = psiClass.getQualifiedName();
                if (inheritorQName == null) {
                    return true;
                }
                return consumer.process(new TargetType(inheritorQName, false, new PsiImmediateClassType(psiClass, PsiSubstitutor.EMPTY)));
            });
        }
    }
    final List<MethodsChain> chains = searchResult.size() > MAX_CHAIN_SIZE ? chooseHead(searchResult) : searchResult;
    return MethodsChainLookupRangingHelper.chainsToWeightableLookupElements(filterTailAndGetSumLastMethodOccurrence(chains), completionContext);
}
Also used : PsiImmediateClassType(com.intellij.psi.impl.source.PsiImmediateClassType) java.util(java.util) ModuleUtilCore(com.intellij.openapi.module.ModuleUtilCore) LookupElement(com.intellij.codeInsight.lookup.LookupElement) com.intellij.compiler.classFilesIndex.chainsSearch(com.intellij.compiler.classFilesIndex.chainsSearch) MethodsUsageIndexReader(com.intellij.compiler.classFilesIndex.impl.MethodsUsageIndexReader) ElementPattern(com.intellij.patterns.ElementPattern) com.intellij.codeInsight.completion(com.intellij.codeInsight.completion) ClassFilesIndexFeaturesHolder(com.intellij.compiler.classFilesIndex.api.index.ClassFilesIndexFeaturesHolder) ContextUtil(com.intellij.compiler.classFilesIndex.chainsSearch.context.ContextUtil) Nullable(org.jetbrains.annotations.Nullable) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) ChainCompletionContext(com.intellij.compiler.classFilesIndex.chainsSearch.context.ChainCompletionContext) TargetType(com.intellij.compiler.classFilesIndex.chainsSearch.context.TargetType) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Project(com.intellij.openapi.project.Project) CompletionContributorPatternUtil(com.intellij.compiler.classFilesIndex.chainsSearch.completion.CompletionContributorPatternUtil) com.intellij.psi(com.intellij.psi) com.intellij.util(com.intellij.util) NotNull(org.jetbrains.annotations.NotNull) DirectClassInheritorsSearch(com.intellij.psi.search.searches.DirectClassInheritorsSearch) ClassFilesIndexFeature(com.intellij.compiler.classFilesIndex.api.index.ClassFilesIndexFeature) PsiJavaPatterns.or(com.intellij.patterns.PsiJavaPatterns.or) Project(com.intellij.openapi.project.Project) PsiImmediateClassType(com.intellij.psi.impl.source.PsiImmediateClassType) TargetType(com.intellij.compiler.classFilesIndex.chainsSearch.context.TargetType) MethodsUsageIndexReader(com.intellij.compiler.classFilesIndex.impl.MethodsUsageIndexReader)

Example 2 with PsiImmediateClassType

use of com.intellij.psi.impl.source.PsiImmediateClassType in project intellij-community by JetBrains.

the class AnnotationsHighlightUtil method doCheckRepeatableAnnotation.

@Nullable
private static String doCheckRepeatableAnnotation(@NotNull PsiAnnotation annotation) {
    PsiAnnotationOwner owner = annotation.getOwner();
    if (!(owner instanceof PsiModifierList))
        return null;
    PsiElement target = ((PsiModifierList) owner).getParent();
    if (!(target instanceof PsiClass) || !((PsiClass) target).isAnnotationType())
        return null;
    PsiClass container = getRepeatableContainer(annotation);
    if (container == null)
        return null;
    PsiMethod[] methods = container.findMethodsByName("value", false);
    if (methods.length == 0) {
        return JavaErrorMessages.message("annotation.container.no.value", container.getQualifiedName());
    }
    if (methods.length == 1) {
        PsiType expected = new PsiImmediateClassType((PsiClass) target, PsiSubstitutor.EMPTY).createArrayType();
        if (!expected.equals(methods[0].getReturnType())) {
            return JavaErrorMessages.message("annotation.container.bad.type", container.getQualifiedName(), JavaHighlightUtil.formatType(expected));
        }
    }
    RetentionPolicy targetPolicy = getRetentionPolicy((PsiClass) target);
    if (targetPolicy != null) {
        RetentionPolicy containerPolicy = getRetentionPolicy(container);
        if (containerPolicy != null && targetPolicy.compareTo(containerPolicy) > 0) {
            return JavaErrorMessages.message("annotation.container.low.retention", container.getQualifiedName(), containerPolicy);
        }
    }
    Set<PsiAnnotation.TargetType> repeatableTargets = AnnotationTargetUtil.getAnnotationTargets((PsiClass) target);
    if (repeatableTargets != null) {
        Set<PsiAnnotation.TargetType> containerTargets = AnnotationTargetUtil.getAnnotationTargets(container);
        if (containerTargets != null && !repeatableTargets.containsAll(containerTargets)) {
            return JavaErrorMessages.message("annotation.container.wide.target", container.getQualifiedName());
        }
    }
    return null;
}
Also used : PsiImmediateClassType(com.intellij.psi.impl.source.PsiImmediateClassType) RetentionPolicy(java.lang.annotation.RetentionPolicy) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with PsiImmediateClassType

use of com.intellij.psi.impl.source.PsiImmediateClassType in project intellij-community by JetBrains.

the class TypeMigrationLabeler method addMigrationRoot.

boolean addMigrationRoot(PsiElement element, PsiType type, final PsiElement place, boolean alreadyProcessed, final boolean isContraVariantPosition, final boolean userDefinedType) {
    if (type.equals(PsiType.NULL)) {
        return false;
    }
    final PsiElement resolved = Util.normalizeElement(element);
    if (!canBeRoot(resolved, myRules.getSearchScope())) {
        return false;
    }
    final PsiType originalType = getElementType(resolved);
    LOG.assertTrue(originalType != null);
    type = userDefinedType ? type : TypeEvaluator.substituteType(type, originalType, isContraVariantPosition);
    if (!userDefinedType) {
        final Set<PsiTypeParameter> collector;
        if (type instanceof PsiClassType) {
            collector = type.accept(new PsiExtendedTypeVisitor<Set<PsiTypeParameter>>() {

                private final Set<PsiTypeParameter> myResult = new HashSet<>();

                @Override
                public Set<PsiTypeParameter> visitClassType(PsiClassType classType) {
                    super.visitClassType(classType);
                    final PsiClass resolved = classType.resolve();
                    if (resolved instanceof PsiTypeParameter) {
                        myResult.add((PsiTypeParameter) resolved);
                    }
                    return myResult;
                }
            });
        } else {
            collector = Collections.emptySet();
        }
        if (typeContainsTypeParameters(originalType, collector))
            return false;
    }
    if (type instanceof PsiCapturedWildcardType) {
        return false;
    }
    if (resolved instanceof PsiMethod) {
        final PsiMethod method = ((PsiMethod) resolved);
        final PsiClass containingClass = method.getContainingClass();
        if (containingClass instanceof PsiAnonymousClass) {
            final HierarchicalMethodSignature signature = method.getHierarchicalMethodSignature();
            final List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures();
            if (!superSignatures.isEmpty()) {
                final HierarchicalMethodSignature superSignature = superSignatures.get(0);
                final PsiSubstitutor substitutor = superSignature.getSubstitutor();
                if (!substitutor.getSubstitutionMap().isEmpty()) {
                    final PsiMethod superMethod = superSignature.getMethod();
                    final PsiType superReturnType = superMethod.getReturnType();
                    if (superReturnType instanceof PsiClassType) {
                        final PsiClass resolvedClass = ((PsiClassType) superReturnType).resolve();
                        if (resolvedClass instanceof PsiTypeParameter) {
                            final PsiType expectedReturnType = substitutor.substitute((PsiTypeParameter) resolvedClass);
                            if (Comparing.equal(expectedReturnType, method.getReturnType())) {
                                final PsiClassType baseClassType = ((PsiAnonymousClass) containingClass).getBaseClassType();
                                final PsiClassType.ClassResolveResult result = baseClassType.resolveGenerics();
                                final PsiClass anonymousBaseClass = result.getElement();
                                final PsiSubstitutor superHierarchySubstitutor = TypeConversionUtil.getClassSubstitutor(superMethod.getContainingClass(), anonymousBaseClass, PsiSubstitutor.EMPTY);
                                final PsiType maybeTypeParameter = superHierarchySubstitutor.substitute((PsiTypeParameter) resolvedClass);
                                if (maybeTypeParameter instanceof PsiClassType && ((PsiClassType) maybeTypeParameter).resolve() instanceof PsiTypeParameter) {
                                    final PsiSubstitutor newSubstitutor = result.getSubstitutor().put((PsiTypeParameter) ((PsiClassType) maybeTypeParameter).resolve(), type);
                                    addRoot(new TypeMigrationUsageInfo(((PsiAnonymousClass) containingClass).getBaseClassReference().getParameterList()), new PsiImmediateClassType(anonymousBaseClass, newSubstitutor), place, alreadyProcessed);
                                }
                            }
                        }
                    }
                }
            }
        }
        final PsiMethod[] methods = OverridingMethodsSearch.search(method).toArray(PsiMethod.EMPTY_ARRAY);
        final OverriderUsageInfo[] overriders = new OverriderUsageInfo[methods.length];
        for (int i = -1; i < methods.length; i++) {
            final TypeMigrationUsageInfo m;
            if (i < 0) {
                final OverriddenUsageInfo overriddenUsageInfo = new OverriddenUsageInfo(method);
                m = overriddenUsageInfo;
                final String newMethodName = isMethodNameCanBeChanged(method);
                if (newMethodName != null) {
                    final MigrateGetterNameSetting migrateGetterNameSetting = myRules.getConversionSettings(MigrateGetterNameSetting.class);
                    migrateGetterNameSetting.askUserIfNeed(overriddenUsageInfo, newMethodName, myTypeEvaluator.getType(myCurrentRoot));
                }
            } else {
                overriders[i] = new OverriderUsageInfo(methods[i], method);
                m = overriders[i];
            }
            alreadyProcessed = addRoot(m, type, place, alreadyProcessed);
        }
        return !alreadyProcessed;
    } else if (resolved instanceof PsiParameter && ((PsiParameter) resolved).getDeclarationScope() instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) ((PsiParameter) resolved).getDeclarationScope();
        final int index = method.getParameterList().getParameterIndex(((PsiParameter) resolved));
        final PsiMethod[] methods = OverridingMethodsSearch.search(method).toArray(PsiMethod.EMPTY_ARRAY);
        final OverriderUsageInfo[] overriders = new OverriderUsageInfo[methods.length];
        final OverriddenUsageInfo overriddenUsageInfo = new OverriddenUsageInfo(method.getParameterList().getParameters()[index]);
        for (int i = -1; i < methods.length; i++) {
            final PsiMethod m = i < 0 ? method : methods[i];
            final PsiParameter p = m.getParameterList().getParameters()[index];
            final TypeMigrationUsageInfo paramUsageInfo;
            if (i < 0) {
                paramUsageInfo = overriddenUsageInfo;
            } else {
                overriders[i] = new OverriderUsageInfo(p, method);
                paramUsageInfo = overriders[i];
            }
            alreadyProcessed = addRoot(paramUsageInfo, type, place, alreadyProcessed);
        }
        return !alreadyProcessed;
    } else {
        return !addRoot(new TypeMigrationUsageInfo(resolved), type, place, alreadyProcessed);
    }
}
Also used : PsiImmediateClassType(com.intellij.psi.impl.source.PsiImmediateClassType) TypeMigrationUsageInfo(com.intellij.refactoring.typeMigration.usageInfo.TypeMigrationUsageInfo) PsiExtendedTypeVisitor(com.intellij.refactoring.typeCook.deductive.PsiExtendedTypeVisitor) OverriddenUsageInfo(com.intellij.refactoring.typeMigration.usageInfo.OverriddenUsageInfo) OverriderUsageInfo(com.intellij.refactoring.typeMigration.usageInfo.OverriderUsageInfo)

Example 4 with PsiImmediateClassType

use of com.intellij.psi.impl.source.PsiImmediateClassType in project intellij-community by JetBrains.

the class JavaMethodsConflictResolver method isApplicableTo.

private boolean isApplicableTo(@NotNull PsiType[] types2AtSite, @NotNull PsiMethod method1, @NotNull final LanguageLevel languageLevel, boolean varargsPosition, @NotNull PsiSubstitutor methodSubstitutor1, @NotNull PsiMethod method2, final PsiSubstitutor siteSubstitutor1) {
    if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8) && method1.getTypeParameters().length > 0 && myArgumentsList instanceof PsiExpressionList) {
        final PsiElement parent = myArgumentsList.getParent();
        if (parent instanceof PsiCallExpression) {
            return InferenceSession.isMoreSpecific(method2, method1, siteSubstitutor1, ((PsiExpressionList) myArgumentsList).getExpressions(), myArgumentsList, varargsPosition);
        }
    }
    final PsiUtil.ApplicabilityChecker applicabilityChecker = new PsiUtil.ApplicabilityChecker() {

        @Override
        public boolean isApplicable(PsiType left, PsiType right, boolean allowUncheckedConversion, int argId) {
            if (right instanceof PsiClassType) {
                final PsiClass rightClass = ((PsiClassType) right).resolve();
                if (rightClass instanceof PsiTypeParameter) {
                    right = new PsiImmediateClassType(rightClass, siteSubstitutor1);
                }
            }
            return languageLevel.isAtLeast(LanguageLevel.JDK_1_8) ? isTypeMoreSpecific(left, right, argId) : TypeConversionUtil.isAssignable(left, right, allowUncheckedConversion);
        }
    };
    final int applicabilityLevel = PsiUtil.getApplicabilityLevel(method1, methodSubstitutor1, types2AtSite, languageLevel, false, varargsPosition, applicabilityChecker);
    return applicabilityLevel > MethodCandidateInfo.ApplicabilityLevel.NOT_APPLICABLE;
}
Also used : PsiImmediateClassType(com.intellij.psi.impl.source.PsiImmediateClassType)

Example 5 with PsiImmediateClassType

use of com.intellij.psi.impl.source.PsiImmediateClassType in project intellij-community by JetBrains.

the class ChangeTypeSignatureTest method doTest.

private void doTest(boolean success, String migrationTypeText) throws Exception {
    String dataPath = "/refactoring/changeTypeSignature/";
    configureByFile(dataPath + getTestName(false) + ".java");
    final PsiFile file = getFile();
    final PsiElement element = file.findElementAt(getEditor().getCaretModel().getOffset());
    final PsiReferenceParameterList parameterList = PsiTreeUtil.getParentOfType(element, PsiReferenceParameterList.class);
    assert parameterList != null;
    final PsiClass superClass = (PsiClass) ((PsiJavaCodeReferenceElement) parameterList.getParent()).resolve();
    assert superClass != null;
    PsiType migrationType = getJavaFacade().getElementFactory().createTypeFromText(migrationTypeText, null);
    try {
        final TypeMigrationRules rules = new TypeMigrationRules();
        rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
        new TypeMigrationProcessor(getProject(), new PsiElement[] { parameterList }, Functions.<PsiElement, PsiType>constant(PsiSubstitutor.EMPTY.put(superClass.getTypeParameters()[0], migrationType).substitute(new PsiImmediateClassType(superClass, PsiSubstitutor.EMPTY))), rules).run();
        if (success) {
            checkResultByFile(dataPath + getTestName(false) + ".java.after");
        } else {
            fail("Conflicts should be detected");
        }
    } catch (RuntimeException e) {
        if (success) {
            e.printStackTrace();
            fail("Conflicts should not appear");
        }
    }
}
Also used : TypeMigrationRules(com.intellij.refactoring.typeMigration.TypeMigrationRules) PsiImmediateClassType(com.intellij.psi.impl.source.PsiImmediateClassType) TypeMigrationProcessor(com.intellij.refactoring.typeMigration.TypeMigrationProcessor)

Aggregations

PsiImmediateClassType (com.intellij.psi.impl.source.PsiImmediateClassType)9 NotNull (org.jetbrains.annotations.NotNull)2 Nullable (org.jetbrains.annotations.Nullable)2 com.intellij.codeInsight.completion (com.intellij.codeInsight.completion)1 LookupElement (com.intellij.codeInsight.lookup.LookupElement)1 ClassFilesIndexFeature (com.intellij.compiler.classFilesIndex.api.index.ClassFilesIndexFeature)1 ClassFilesIndexFeaturesHolder (com.intellij.compiler.classFilesIndex.api.index.ClassFilesIndexFeaturesHolder)1 com.intellij.compiler.classFilesIndex.chainsSearch (com.intellij.compiler.classFilesIndex.chainsSearch)1 CompletionContributorPatternUtil (com.intellij.compiler.classFilesIndex.chainsSearch.completion.CompletionContributorPatternUtil)1 ChainCompletionContext (com.intellij.compiler.classFilesIndex.chainsSearch.context.ChainCompletionContext)1 ContextUtil (com.intellij.compiler.classFilesIndex.chainsSearch.context.ContextUtil)1 TargetType (com.intellij.compiler.classFilesIndex.chainsSearch.context.TargetType)1 MethodsUsageIndexReader (com.intellij.compiler.classFilesIndex.impl.MethodsUsageIndexReader)1 ApplicationManager (com.intellij.openapi.application.ApplicationManager)1 ModuleUtilCore (com.intellij.openapi.module.ModuleUtilCore)1 Project (com.intellij.openapi.project.Project)1 Pair (com.intellij.openapi.util.Pair)1 ElementPattern (com.intellij.patterns.ElementPattern)1 PsiJavaPatterns.or (com.intellij.patterns.PsiJavaPatterns.or)1 com.intellij.psi (com.intellij.psi)1